Home

Blog

React useEffect, Done Right

React useEffect, Done Right

Effects synchronize

useEffect isn't β€œrun after render” β€” it's β€œkeep this external thing in sync with these values.” List every value you read in the dependency array, and clean up whatever you set up:

useEffect(() => {
  const id = setInterval(tick, 1000);
  return () => clearInterval(id);
}, [tick]);

If an effect doesn't depend on any prop or state, it probably shouldn't be an effect at all.

More posts