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
- Correct dependencies: list every reactive value in
useEffect,useCallbackanduseMemodependency arrays, so functions are recreated with fresh values. Theexhaustive-depslint rule helps. - Updater functions:
setCount((c) => c + 1)reads the latest state without capturingcount. 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.- Refs: store the latest value in a ref (
latest.current = valuein an effect) and read the ref in long-lived callbacks. The older pattern, now mostly replaced byuseEffectEvent. 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
1import { useEffect, useEffectEvent, useState } from "react";23export function StaleDemo({ userName }: { userName: string }) {4 const [count, setCount] = useState(0);56 // Bug: stale closure, count is always 0 inside the interval7 // useEffect(() => {8 // const id = setInterval(() => setCount(count + 1), 1000);9 // return () => clearInterval(id);10 // }, []);1112 // Fix 1: updater function13 useEffect(() => {14 const id = setInterval(() => setCount((c) => c + 1), 1000);15 return () => clearInterval(id);16 }, []);1718 // Fix 2 (React 19.2): Effect Event reads the latest userName and count19 const logTick = useEffectEvent(() => {20 console.log(`${userName} has watched for ${count}s`);21 });2223 useEffect(() => {24 const id = setInterval(logTick, 5000); // not restarted when userName or count change25 return () => clearInterval(id);26 }, []);2728 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.