Skip to content

QuizNot attempted

setInterval with a functional update

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

Correct answer:

  • 5
  • The updater c => c + 1 doesn't read the closed-over count
  • React passes the current state each tick, so one stale callback still increments correctly: 5 ticks → 5.
  • Not 0 or 1: those are stale-closure outcomes, and the updater avoids the stale read.
  • Not undefined behaviour: this is the recommended pattern
  • the cleanup clears the interval on unmount.