MediumHooks & Closures💻 Output Question

Stale closure in setInterval — count never updates

💡

Hint

In React, a useEffect callback that closes over state will see the state value at the time it was created — not future updates. This is the stale closure bug that requires functional updates or refs.

What does this output?

// Simulates the stale closure bug in useEffect + setInterval
let count = 0;

function startInterval() {
  const capturedCount = count; // closure captures value at call time

  const tick = () => {
    // This function always reads 'capturedCount', not the live 'count'
    console.log('tick sees:', capturedCount);
  };

  count = 5;       // "state update" after interval set up
  tick();
  count = 10;
  tick();
}

startInterval();

Correct Output

tick sees: 0
tick sees: 0

Why this output?

Explanation: capturedCount is assigned 0 (the value of count at capture time). Subsequent changes to count don't affect capturedCount — the closure holds the old value.

Key Insight: In React, a useEffect callback that closes over state will see the state value at the time it was created — not future updates. This is the stale closure bug that requires functional updates or refs.

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz