Skip to content
engineering workbench.by StudyPort Academy
All errors
logic · DEBUG LIBRARY

Stale state inside an effect or callback

Locate the failed assumption, reproduce it, then repair the cause.

What actually caused it

A closes over the state and props from the render that created it. If that function runs later - a timer, a , or an effect whose dependency list omitted the value - it still sees the old render. The screen can show a new count while the logs the count from when the effect last ran.

This is ordinary JavaScript, not a React quirk. React’s dependency list is how you tell it which closed-over values should cause the to be recreated. An empty list means “the first render’s values, for the life of this component.”

Minimal reproduction

An interval that keeps the first count

useEffect(() => {
  const id = setInterval(() => {
    console.log(count);
  }, 1000);
  return () => clearInterval(id);
}, []);

count is always the value from the first render.

The fix

List every reactive value the effect or reads in its dependency , or restructure so the latest value is not needed. For a frequent update, a functional setState update (setCount(c => c + 1)) does not need the current count in the .

When a must see the latest , store it in a ref that you update during render, or include the callback in the dependency list and keep the callback stable on purpose. After the fix, change the state and confirm the delayed callback observes the new value.

Recreate the interval when count changes

useEffect(() => {
  const id = setInterval(() => {
    console.log(count);
  }, 1000);
  return () => clearInterval(id);
}, [count]);

The cleanup clears the old interval before the new one starts.