DEV Community

An Opiniated React Stack

Simplicity & Aesthetics over Complexity
Life is too sweet to be loosing sleep over trying to understand how a library or framework works, as long as a solution or library is working and has long term support I'm okay with it

Recoil JS

Example with async queries

using useRecoilValueLoadable hook.

This hook is intended to be used for reading the value of asynchronous selectors. This hook will implicitly subscribe the component to the given state.

This hooks returns a Loadable object for the current state with the following interface:

  • state: Indicates the status of the selector. Possible values are 'hasValue', 'hasError', 'loading'.
  • contents: The value represented by this Loadable. If the state is 'hasValue', it is the actual value, if the state is 'hasError' it is the Error object that was thrown, and if the state is 'loading', then it is a Promise of the value.

The example code below implements useRecoilValueLoadable hook from recoilJS using Next JS, in a use-case when implementing private routes using HOC

import { useRouter } from "next/router";
import React from "react";
import { useRecoilValueLoadable } from "recoil";
import getAuthUser from "../store/selectors/getAuthUser";

const withAuthConsumer = (WrappedComponent: any) => {
  return (props: any) => {
    const authUser = useRecoilValueLoadable(getAuthUser);
    const router = useRouter();

    // checks whether we are on client / browser or server.
    if (typeof window !== "undefined") {
      if (authUser.state == "loading") {
        return null;

      if (
        authUser.state == "hasValue" &&
        authUser.contents?.user_type == "consumer"
      ) {
        return <WrappedComponent {...props} />;
      } else if (
        authUser.state == "hasValue" &&
        authUser.contents?.user_type == null
      ) {
        return null;
      } else {
        return null;
    // If we are on server, return null
    return null;

export default withAuthConsumer;
Enter fullscreen mode Exit fullscreen mode

Check this useRecoilValueLoadable for more explanation.

Html to jsx

Discussion (0)