Stale Closures in React Hooks: Why Your State Is Old
A stale closure in React is a function that keeps using the state or props from the render where it was created, even after newer renders have changed them. It's why a setInterval or a delayed handler can show an old value.
If you've ever written setCount(count + 1) inside a timer and watched the number get stuck at 1, this is for you.
The idea: every render is a snapshot
Before the bug, one idea. When React renders your component, it calls your function. Inside that call, count is just a normal variable with one fixed value. The next render is a separate call with its own count.
Any function you create during a render, like an event handler or an effect, can read the variables around it. That's what a closure is: a function that remembers the variables from where it was made. If you want a refresher, see closures in JavaScript.
So a function made in render 1 remembers count = 0. It will keep remembering 0, even after render 3 where count is 2. That old remembered value is the "stale" part.
Here's the simplest way to see it:
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
setTimeout(() => {
alert(count);
}, 3000);
}
return <button onClick={handleClick}>Clicked {count} times</button>;
}
Click once and the screen goes to 1. After three seconds the alert says 0. The timer callback was created in the render where count was 0, so that's what it reads. React's docs describe state this way: a state variable's value never changes within one render.
Walkthrough: the stuck interval
The most common version is a counter that should tick every second:
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(count + 1); // reads count from the first render
}, 1000);
return () => clearInterval(id);
}, []);
return <p>{count}</p>;
}
Step by step:
- First render.
countis 0. The effect runs once (because of[]) and creates an interval. Its callback closes overcount = 0. - One second later. The callback runs
setCount(0 + 1). The screen shows 1. - React re-renders.
countis now 1, but the effect doesn't run again, because its dependencies didn't change. The interval still holds the callback from step 1. - Every tick after that. The old callback runs
setCount(0 + 1)again. Setting 1 when it's already 1 changes nothing.
Notice that React did nothing wrong. We told it "run this effect once", and it did.
Three ways to fix it
1. Use an updater function
If you're computing new state from the old state, pass a function to the setter. React calls it with the latest pending state, so your callback doesn't need to read count at all:
useEffect(() => {
const id = setInterval(() => {
setCount((c) => c + 1);
}, 1000);
return () => clearInterval(id);
}, []);
Now count isn't used inside the effect, so [] is correct and the interval is created only once. This is the best fix when it applies.
2. Add the value to the dependency array
If the effect really needs the value, list it:
useEffect(() => {
const id = setInterval(() => {
console.log('count is', count);
}, 1000);
return () => clearInterval(id);
}, [count]);
Each time count changes, React runs the cleanup function, then sets up a fresh interval with a fresh closure. It's correct, but the interval restarts on every change, which is a problem for something like a timer that should tick steadily.
3. Read the latest value from a ref
A ref (useRef) is one object that stays the same across renders. Reading ref.current always gives whatever you stored last, so an old callback can still see the latest value.
function Logger() {
const [count, setCount] = useState(0);
const countRef = useRef(count);
useEffect(() => {
countRef.current = count;
}, [count]);
useEffect(() => {
const id = setInterval(() => {
console.log('count is', countRef.current);
}, 1000);
return () => clearInterval(id);
}, []);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
The interval is created once and never restarts, but it always logs the current count. Updating the ref inside an effect, rather than during rendering, keeps the component pure.
Examples
1. A button that "loses" clicks
function handleClick() {
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
}
Problem: one click adds 1, not 3.
Why: all three calls read the same count from this render's snapshot. Each one says "set to count + 1", which is the same number.
Fix: use updaters, so each call builds on the previous result.
function handleClick() {
setCount((c) => c + 1);
setCount((c) => c + 1);
setCount((c) => c + 1);
}
2. A WebSocket handler with old props
useEffect(() => {
const socket = new WebSocket(url);
socket.onmessage = (event) => {
if (filter === 'all') addMessage(event.data);
};
return () => socket.close();
}, [url]);
Problem: after the user changes filter, the handler still behaves as if it were the old filter.
Why: the effect depends only on url, so the handler was created with the first filter and never replaced.
Fix: add filter to the dependencies if reconnecting is acceptable. If not, store the filter in a ref and read filterRef.current in the handler.
3. A debounced search that uses old text
const debounced = useMemo(
() => debounce(() => search(query), 300),
[]
);
Problem: the search always runs with the first query, usually an empty string.
Why: useMemo with [] creates the function once, and it closes over the first render's query.
Fix: pass the value as an argument, debounced(query), instead of reading it from the closure.
Interview answer
A stale closure happens when a function created in one render keeps using that render's state or props after newer renders have different values. Each render is a snapshot, and callbacks like timers, event listeners and effects close over the values from the render that created them. The classic case is setInterval inside useEffect with an empty dependency array. I fix it with an updater function like setCount(c => c + 1), by adding the value to the dependency array, or by reading the latest value from a ref.
Summary
- Every render is a snapshot:
counthas one fixed value inside that render. - A closure remembers the variables from where the function was created.
- A function created in an old render keeps the old values. That's a stale closure.
- It's not a React bug. It's how closures and renders work together.
- Typical places:
setInterval,setTimeout, event listeners and effects with missing dependencies. - An updater function (
setCount(c => c + 1)) is the best fix for state based on old state. - Adding the value to the dependency array makes the effect re-run with a fresh closure.
- A ref gives callbacks the latest value without re-running the effect, but it doesn't trigger re-renders.
- Don't silence
exhaustive-depswarnings without understanding why they appear. - Calling
setCount(count + 1)three times in a row still adds only 1.