DEV Community

vobie
vobie

Posted on

Conditional state update in useEffect

useEffect(() => {
  unsub = asyncFetch((d) => {
    setState(s => {
        if(deepEqual(d,s))
           return s
        else return d
     })
  })
  return unsub;
}, [])
Enter fullscreen mode Exit fullscreen mode

This is what I want to do, but this code assumes that if I return s, then the state update won't trigger a rerender of the component. What's the best way to achieve this?

If I simply check against the state (conditional wrapping setState) instead of using s from the setState, I will always get the initial state set by useState. What I'm doing now is using useRef to always update a ref with the latest state so that I can access it in the callback, but I'm unsure if this can have unintended consequences as setState is asynchronous and I don't know if the effect will always run first thing after the state is updated to keep the ref in sync. What I would really need is a version of setState that allows returning a special value to abort the state update.

Thanks for your help.

Discussion (0)