QuizNot attempted
Stale closure in a delayed log
1–4 to choose, Enter to submit
Show answer & explanation
Correct answer:
after 3s, count is: 0— the stale closure capturedcountas it was at the timeincrementwas called (the first click), demonstrating the classic stale closure pitfall
- Each render's
incrementcloses over that render'scount - the first click ran in the render where
count = 0, so its timeout logs0three 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:
countis in scope via the closure. - Use a ref to read the latest value.