DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 967,611 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Michael Di Prisco
Michael Di Prisco

Posted on

I wasn't happy with React useState Hook, so I built my own one and made it Open Source.

Link to my project, please star it if you like it!

Some days ago I was working with React and, for the 1000th time, I got myself in trouble with the stale state problem.

What is the stale state problem?

The stale state problem is when you have a useState and update the corresponding state using the hook's given setState function. Until React rerenders the component, your state will be stale, meaning that it will not be updated.

Here's an example of a stale state:

const [count, setCount] = useState(0)
setCount(count + 1);
console.log(count); // Expecting 1, receiving 0 instead.
setTimeout(() => {
  setCount(count + 1);
}, 1000); // Expecting 2, receiving 1 instead.
Enter fullscreen mode Exit fullscreen mode

As mentioned, the above code will not work as expected, because the state will be stale until React re-renders the component.

This is because React re-creates the component function at every re-render, effectively preventing a consistent reference for variables.

This is where useAtom comes in.

By using a mix of React's state mechanism, Proxy Pattern and Observer Pattern, useAtom allows the state to be completely and fully reactive, preventing the stale state issue mentioned above.

By doing this, we can be sure that the state is always up to date, even if React hasn't re-rendered the component yet.
Example:

const atomTest = useAtom(0);
console.log(atomTest.value); // 0, as expected
atomTest.value++;
console.log(atomTest.value); // 1, as expected
setTimeout(() => {
  atomTest.value++;
}, 1000); // 2, as expected
Enter fullscreen mode Exit fullscreen mode

The above code will work as expected, because the state is not stale. The useAtom hook will update the state immediately, and the value property will be updated as well.

What can I put in an atom?

You can use the useAtom hook both with primitives (strings, numbers, etc..), arrays and objects. It cannot be used with functions.

Internally, the hook will create an atom for every primitive in the array or in the object.

  const atomObj = useAtom({
    a: 1,
    b: 10,
    c: 100,
  });

  atomObj.a.value = 2; // This will update the state
  console.log(atomObj.a.value); // 2, as expected

  const atomArr = useAtom([1, 2, 3, 4, 5]);

  atomArr[0].value = 10; // This will update the state
  console.log(atomArr[0].value); // 10, as expected
Enter fullscreen mode Exit fullscreen mode

What is the difference between useAtom and useState?

The difference is that useAtom will update the state variable immediately thanks to its Proxy-based implementation, while useState will not update it until React re-renders the component.

What is the difference between useAtom and useRef?

The difference is that useAtom will re-render the component on change, while useRef will not.

How can I subscribe for changes?

If you want to respect the Observer Pattern, you can use the subscribe method to subscribe and unsubscribe for changes:

const atomTest = useAtom(0);
const atomObserver = (newValue, oldValue) => {
  console.log(`New value: ${newValue}, old value: ${oldValue}`);
};
atomTest.subscribe(atomObserver);
atomTest.value++;
atomTest.unsubscribe(atomObserver);
Enter fullscreen mode Exit fullscreen mode

What if I want to keep using the useEffect hook?

If you instead prefer a more standard approach, the hook exposes a state property which contains the React state value, allowing you to use the useEffect hook as usual.

const atomTest = useAtom(0);
useEffect(() => {
  console.log(`New value: ${atomTest.state}`);
}, [atomTest.state]);
atomTest.value++;
Enter fullscreen mode Exit fullscreen mode

How can I trigger my subscribe callback at first component mount?

You can pass a second parameter to the useAtom hook, which will contain the atom configuration.

You can use the triggerOnMount property to trigger the subscribe callback at first component mount.

This will work in a similar way to a Behaviour Subject in Reactive Programming and works just like the useEffect hook.

const atomTest = useAtom(0, {
  triggerSubscribeOnMount: true,
});
atomTest.subscribe((newValue, oldValue) => {
  console.log(`New value: ${newValue}, old value: ${oldValue}`);
}); // This will be logged at first component mount with initial value of 0.
Enter fullscreen mode Exit fullscreen mode

Please, let me know what you think about my implementation and please, share some use cases in which the useAtom hook helped you!

Top comments (2)

Collapse
 
marklai1998 profile image
Mark Lai

I dont understand the propose of this hook
For the stale state problem I think it against react philosophy, the only usage I can think of is to track the re-render of the component? Anyway I won't debate here

But for the implementation, first come to my mind is useRef, but you said it will rerender the component. So I took a look into your code, ultimatly you're just using useState for the re-render, then I just dont see the point of using a fancy "proxy" here. I can just rewrite it with a few line of code

const useAtom = (initialState) =>{
  const refState = useRef(initialState)
  const [state, setState] = useState(initialState)

  return {
    value: refState.current,
    state,
    setState: (newState)=>{
      refState.current = newState
      setState(newState)
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

I would like to know whats the real reason for the Proxy here,
May be subscription? useEffect can also act like subscription. Also I want to know how will you use the subscription in real live, your subscribe and unsub needs to wrap in useEffect anyway

Collapse
 
cadienvan profile image
Michael Di Prisco Author

As per your first point, if you ever needed to delay a setState and then use the new value in the same call stack, you know it's not possible only using the state. Having to use a state + a ref for this situation is just a hack, and I didn't want that. The stale state problem isn't part of React philosophy, it's just a necessary evil.

As per the proxy implementation, I never liked the "setState" function mechanism, I wanted something TRULY reactive. This also answers about your rewrite.

The observer pattern (sub/unsub) is a mechanism that can be very useful for certain use cases, first of all if you need to do something BEFORE React rerenders the component. What if you need to update a second state when the atom updates? A useEffect would need 2 rerenders, 1 for the first state and 1 for the second one, by using the atom you only have 1 rerender instead.

Another important difference in my implementation is the "previousValue", which isn't available in the useState hook.

You brought some good points on the table and I'd love to know if my comment answered your questions and convinced you or if you still have some doubts, I love meaningful discussion.

All-time great DEV bookmarkable post:

How web browsers work (with illustrations)

Seriously, one of the best series of the year