DEV Community 👩‍💻👨‍💻

Nic
Nic

Posted on

React: running something only after state hook has updated

Hooks in React are great. It's such much easier than the old class method of sending state down to the children - you can just write it all in the component. Except that it doesn't update instantly. It looks like it's instant, but computers work quicker than humans and you can get some weird things going on if you assume the state has updated when it actually hasn't. Isn't programming fun?

Fortunately, there's a solution, using the useEffect hook.

useEffect(()=>{
  doSomething();
},[state])

Enter fullscreen mode Exit fullscreen mode

useEffect will run whenever something updates - we tell it that something is our state. So every time the state updates, useEffect runs and it runs doSomething.

Which is great, except that it runs when the state is set. Including when we set it all up:

const [state setState] = useState();
Enter fullscreen mode Exit fullscreen mode

Which might be what you want, but chances are, it's not.

Fortunately, another function comes to our rescue: useRef:

const firstRender = React.useRef(false);
useEffect(()=>{
  if(firstRender.current) {
    doSomething();
  } else {
    firstRender.current = true;
  }
},[state])
Enter fullscreen mode Exit fullscreen mode

What happens here is that the first time useEffect runs - when the state is first set up - it only sets firstRender to be true. After that, it'll always run doSomething.

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.