ReactMedium

What is a stale closure in hooks?

A stale closure happens when a function created during an earlier render keeps using the props or state from that render, even though newer values exist. Common symptoms are an interval that always logs the initial count, or an event listener that sends outdated data.

Why it happens

Each render creates new functions that close over that render's values. If an old function stays alive (registered in a setInterval, a subscription, an effect with missing dependencies, a memoized callback with incomplete deps), it keeps seeing old values.

Fixes

  1. Correct dependencies: list every reactive value in useEffect, useCallback and useMemo dependency arrays, so functions are recreated with fresh values. The exhaustive-deps lint rule helps.
  2. Updater functions: setCount((c) => c + 1) reads the latest state without capturing count.
  3. useEffectEvent (React 19.2): wrap logic that should always read the latest props or state but must not re-trigger an effect. The Effect Event function always sees current values.
  4. Refs: store the latest value in a ref (latest.current = value in an effect) and read the ref in long-lived callbacks. The older pattern, now mostly replaced by useEffectEvent.
  5. useReducer: dispatching actions avoids reading state inside the callback.

Interview example

useEffect(() => { const id = setInterval(() => setCount(count + 1), 1000); return () => clearInterval(id); }, []) stops at 1, because count is always 0 inside the closure. Use setCount((c) => c + 1).

Code example

tsx
1import { useEffect, useEffectEvent, useState } from "react";
2
3export function StaleDemo({ userName }: { userName: string }) {
4 const [count, setCount] = useState(0);
5
6 // Bug: stale closure, count is always 0 inside the interval
7 // useEffect(() => {
8 // const id = setInterval(() => setCount(count + 1), 1000);
9 // return () => clearInterval(id);
10 // }, []);
11
12 // Fix 1: updater function
13 useEffect(() => {
14 const id = setInterval(() => setCount((c) => c + 1), 1000);
15 return () => clearInterval(id);
16 }, []);
17
18 // Fix 2 (React 19.2): Effect Event reads the latest userName and count
19 const logTick = useEffectEvent(() => {
20 console.log(`${userName} has watched for ${count}s`);
21 });
22
23 useEffect(() => {
24 const id = setInterval(logTick, 5000); // not restarted when userName or count change
25 return () => clearInterval(id);
26 }, []);
27
28 return <p>{count}s</p>;
29}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app