Skip to content

FlashcardNot attempted

Stale closures in React

Recall it before you reveal

Why does setCount(count + 1) inside a setInterval in useEffect(..., []) get stuck at 1?

Space to reveal
Show answer & explanation

The interval callback was created in the FIRST render and closes over that render's count (0) forever: a stale closure.

Fixes:

  • functional update: setCount(c => c + 1) (doesn't read the captured value)
  • add count to the deps (re-creates the interval each change)
  • keep the latest value in a useRef