Skip to the page

Effects and synchronisation · mid

Stale closures in effects, timers and callbacks

Every render creates new functions that "see" that render's props and state; a callback kept from an old render (an interval started with [], a debounced handler) keeps reading old values, which is a stale closure.

The notes

What you must know

  • useEffect(() => { const id = setInterval(() => setCount(count + 1), 1000); return () => clearInterval(id); }, []) shows 1 forever: the interval callback closed over count = 0.
  • Fix 1: updater form setCount(c => c + 1); React gives the latest value.
  • Fix 2: keep the latest value or callback in a ref (savedCallback.current = callback after render) and call the ref inside the interval; this is the classic useInterval hook.
  • Fix 3 (React 19.2+): move the "event" logic into useEffectEvent; it always sees the latest props and state and is not a dependency.
  • Adding count to deps works but clears and recreates the interval every tick, which drifts and resets timing.
  • Same bug with debounce/throttle: a debounced function created once keeps the first render's values; created on every render, it loses its timer. Store it in a ref or memo and read latest values through a ref.
  • Stale closures are plain JavaScript closures plus React's per-render snapshots; nothing is "wrong" with React.

The red pen

Common traps: mistake → fix

  • Mistake: "Disable exhaustive-deps and it works"

    Fix: it hides exactly this bug.

  • Mistake: "Recreating setInterval on every render is fine"

    Fix: it drifts and leaks if cleanup is missed.

  • Mistake: "A ref fixes everything"

    Fix: refs are not reactive; the screen will not update from a ref change.

Easy to hard

Questions interviewers ask, easy to hard

  1. What does this timer display after 5 seconds? Fix it three different ways.
  2. Why is "add count to the deps" a weak fix?
  3. Write a useInterval(callback, delay) hook.
  4. How does useEffectEvent help here?
  5. Does the same bug appear with a debounced search handler?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview