DEV Community

Cover image for Use recoil in react custom hooks
Nathaniel
Nathaniel

Posted on

Use recoil in react custom hooks

Recoil is a hot new state management tool from Facebook that handles the state sharing problem gracefully with a minimal API. I recommend everyone check it out. It's an amazing tool that feels very react-y and require little to little to no boilerplate code. I'm not going to cover it too much in this article. Check out the official documentation for more information.

As amazing as it is, the library do have its own limitations. One of the biggest limitation is that the useRecoilState and useRecoilValue hook does not work properly in custom hooks. Since recoil only subscribe and update those values inside react component. We will have to update the value by ourselves.

How? You may ask. It's magic time, let's use useRef

Voilà

import { useEffect, useRef } from 'react';
import { useRecoilState } from 'recoil';
import { someAtom } from './recoilstates/someState';

const yourCustomHook = () => {
  const [someState, setSomeState] = useRecoilState(someAtom);
  const latestSomeState = useRef(someState);

  useEffect(()=> {
    latestSomeState.current = someState;
  },[someState]);

  // I use useEffect here as an example,
  // custom hook can contain any React hooks
  useEffect(()=>{
    // your custom hook logic here
    // use latestSomeState.current for latest value
  });
}
Enter fullscreen mode Exit fullscreen mode

By using useRef, and useEffect, the react component which this hook is used in will be subscribed to recoil state changes. Therefore, you can get the latest version of the state value in the hook.

Top comments (2)

Collapse
 
agdholo profile image
AGD

Is there a more complete example? Thank you

Collapse
 
m3rashid profile image
MD Rashid Hussain

What about state updates 😓😓😓
Please add that section too