DEV Community

Cover image for Use recoil in react custom hooks
Nathaniel
Nathaniel

Posted on

4 4

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

Sentry image

See why 4M developers consider Sentry, โ€œnot bad.โ€

Fixing code doesnโ€™t have to be the worst part of your day. Learn how Sentry can help.

Learn more

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay