Skip to content

QuizNot attempted

Stale count inside setInterval

After 5 seconds, what does the <div> show?
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(count + 1);
}, 1000);
return () => clearInterval(id);
}, []);
return <div>{count}</div>;
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • 1
  • The interval callback is created once (deps []) and closes over the mount render's count = 0, so every tick calls setCount(0 + 1): the first tick sets 1, later ticks set the same value and bail out, and it is stuck at 1.
  • Not 5: that needs c => c + 1 or count in the deps.
  • Not 0: the first tick does update to 1.
  • Not 'keeps incrementing': the stale closure never sees a value above 0.