Sub topic 10
Stale closures and how to avoid them
This chapter assumes you know closures, useState, the dependency array, and cleanup functions from the earlier chapters. It covers one failure that appears when those pieces interact: an effect that keeps reading old values.
Why closures go stale
Every render calls your component function again. Inside that call, props and state variables such as count are constants for that render. They never change. A new render gets new constants.
An effect callback is a function created during a render, so it closes over that render's values. If the effect re-runs, React uses the new callback with the new values. If the effect does not re-run, the old callback stays alive and keeps seeing the old values. That old callback is a stale closure.
A stale closure is rarely a React bug. It is the normal behavior of JavaScript closures combined with an effect that does not re-run when it should.
The classic bug: a timer stuck at 1
import { useEffect, useState } from 'react';
function BrokenTimer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setSeconds(seconds + 1);
}, 1000);
return () => clearInterval(id);
}, []);
return <p>{seconds} seconds elapsed</p>;
}The display goes from 0 to 1 and stays there. The timeline explains why.
From the second tick on, the callback sets the state to 1 again. React sees the same value and skips the update.
Fix 1: use a functional update
If the new state depends only on the previous state, pass an updater function. React supplies the latest value as its argument, so the closure has nothing stale to read.
import { useEffect, useState } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setSeconds((s) => s + 1);
}, 1000);
return () => clearInterval(id);
}, []);
return <p>{seconds} seconds elapsed</p>;
}This is the best fix when it applies. The effect runs once and the interval is never restarted.
Fix 2: list the value as a dependency
If the effect reads a prop or state value that it cannot get through an updater, list the value in the dependency array. The effect then re-runs whenever the value changes. Cleanup tears down the old interval, and a new callback closes over the new value.
import { useEffect, useState } from 'react';
function Ticker({ step }) {
const [total, setTotal] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setTotal((t) => t + step);
}, 1000);
return () => clearInterval(id);
}, [step]);
return <p>Total: {total}</p>;
}Here total is handled by the updater, and step is a dependency. When step changes, the interval restarts with the new value. The cost is that the timer's one-second rhythm resets on each change. For most effects that is acceptable and correct.
Fix 3: keep the latest value in a ref
Sometimes restarting the effect is the wrong behavior. Suppose a component saves a draft every five seconds. Adding draft to the dependencies would reset the timer on every keystroke, and the save might never fire.
A ref is an object whose .current property you can change without causing a re-render. The ref object stays the same across renders, so a closure that holds the ref always reads its current contents.
import { useEffect, useRef } from 'react';
function AutoSave({ draft }) {
const draftRef = useRef(draft);
useEffect(() => {
draftRef.current = draft;
}, [draft]);
useEffect(() => {
const id = setInterval(() => {
console.log('Saving draft:', draftRef.current);
}, 5000);
return () => clearInterval(id);
}, []);
return null;
}Two details matter:
- The ref is updated inside an effect, not in the render body. Writing to a ref during rendering is a side effect, and rendering must stay pure.
- The second effect has an empty dependency array, and the linter accepts it. Refs are stable, so the linter does not require them in the array.
A later chapter covers this pattern in more detail. For now, treat it as a tool for the case where you need the latest value but must not re-run the effect.
The same bug with event listeners
Subscriptions have the same problem. This listener reads count from the first render only:
import { useEffect, useState } from 'react';
function KeyCounter() {
const [count, setCount] = useState(0);
useEffect(() => {
function handleKey(event) {
if (event.key === ' ') {
console.log('Space pressed, count is', count);
setCount(count + 1);
}
}
window.addEventListener('keydown', handleKey);
return () => window.removeEventListener('keydown', handleKey);
}, []);
return <p>Spaces pressed: {count}</p>;
}The log always prints 0, and the counter stops at 1. The fix is the same: list count in the dependencies so the listener is removed and re-added on every change. Re-subscribing is cheap for a DOM listener, so this is a good choice.
useEffect(() => {
function handleKey(event) {
if (event.key === ' ') {
console.log('Space pressed, count is', count);
setCount(count + 1);
}
}
window.addEventListener('keydown', handleKey);
return () => window.removeEventListener('keydown', handleKey);
}, [count]);A snapshot is not always a bug
Closures capturing a render's values is sometimes exactly what you want. Consider this handler:
import { useState } from 'react';
function Message() {
const [text, setText] = useState('');
function handleSend() {
setTimeout(() => {
alert(`Sent: ${text}`);
}, 3000);
}
return (
<>
<input value={text} onChange={(e) => setText(e.target.value)} />
<button onClick={handleSend}>Send</button>
</>
);
}If the user clicks Send and then keeps typing, the alert shows the text as it was at the moment of the click. That matches the user's intent. A stale closure is a problem only when the code should see the latest value and does not. Decide which behavior you want before choosing a fix.
Do not silence the linter
The react-hooks/exhaustive-deps lint rule reports every value an effect reads that is missing from the dependency array. In the broken timer above it warns that seconds is missing. The warning is correct.
Adding // eslint-disable-next-line react-hooks/exhaustive-deps removes the warning and keeps the bug. Use the warning to choose one of the fixes above instead.
Choosing a fix
| Situation | Fix |
|---|---|
| New state is computed from the old state | Functional update (`setX((x) => ...)`) |
| Effect should restart when the value changes | Add the value to the dependency array |
| Effect must not restart, but needs the latest value | Store the value in a ref |
| The value can be computed from other values | Calculate it during rendering, not in the effect |
Common mistakes
- Reading state inside
setInterval,setTimeout, or a Promise callback and assuming it is current. Those callbacks run later, using the values from the render that created them. - Fixing the symptom by removing the dependency that triggers a re-run. That removes the re-run and brings the stale value back.
- Mutating a ref during rendering instead of in an effect or event handler.
- Assuming
setCount(count + 1)called twice in the same handler adds two. Both calls read the samecount. UsesetCount((c) => c + 1)twice instead.
Exercise
The component below logs "Count is 0" every two seconds, even after the button has been clicked several times. Explain why, and rewrite the effect so the log shows the current count without restarting the interval on each click. function Logger() { const [count, setCount] = useState(0); useEffect(() => { const id = setInterval(() => { console.log('Count is', count); }, 2000); return () => clearInterval(id); }, []); return <button onClick={() => setCount(count + 1)}>Clicked {count}</button>; }
Show answer
The effect runs once, on the first render, so the interval callback closes over count = 0 and keeps logging it. To read the latest value without restarting the interval, store count in a ref: create const countRef = useRef(count), add an effect with [count] as its dependencies that sets countRef.current = count, and log countRef.current inside the interval callback. The interval effect keeps its empty dependency array. Adding count to that array would also be correct, but it would restart the interval on every click.
Exercise
A component calls setTotal(total + 1) twice in a row inside one click handler, and the total goes up by 1 instead of 2. Why does this happen, and what is the fix?
Show answer
Both calls read the same total, because the handler closes over the value from the current render. Each call schedules the state to become total + 1, so the second call overwrites the first with the same value. Use functional updates, setTotal((t) => t + 1) twice. React passes the latest pending value into each updater, so the result is 2.