Skip to content

QuizNot attempted

Stale closure in a delayed log

Click the button, then click it again 1 second later (before the first setTimeout fires). What does the first setTimeout's console log print after 3 seconds — the "stale" closure value or the latest state?
function App() {
const [count, setCount] = useState(0);
function increment() {
setCount(count + 1);
setTimeout(() => {
console.log('after 3s, count is:', count);
}, 3000);
}
return <button onClick={increment}>{count}</button>;
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • after 3s, count is: 0 — the stale closure captured count as it was at the time increment was called (the first click), demonstrating the classic stale closure pitfall
  • Each render's increment closes over that render's count
  • the first click ran in the render where count = 0, so its timeout logs 0 three seconds later, regardless of later renders.
  • Not 2: the timeout reads its own captured variable, not live state.
  • Not 1: 1 is the second render's value, captured by the second click's timeout.
  • Not a ReferenceError: count is in scope via the closure.
  • Use a ref to read the latest value.