Intermediate React Interview QuestionsIntermediateScenario
React · Question 45
What is a stale closure bug in a React Effect, and how would you fix it?
Direct answer
A stale closure occurs when an Effect or callback keeps using values captured by an older render because its synchronization logic does not track the values it actually depends on.
Counter.jsx
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
console.log(count);
}, 1000);
return () => clearInterval(id);
}, []); // count is read but omitted
return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}The interval callback was created by the render where count had its old value. Possible fixes depend on the intent: include the reactive dependency, use an updater when updating state from previous state, or use an Effect Event when the logic should read the latest value without re-synchronizing the external subscription.