HardHooks & Closures💻 Output Question

Stale closure in event handler vs ref solution

💡

Hint

A ref's .current is always the latest value because you're reading a property of a stable object. A state variable in a closure is frozen at the render it was created in.

What does this output?

// Stale approach — closes over initial value
function makeStaleHandler(initialCount) {
  let count = initialCount;
  const staleHandler = () => count * 2;  // closes over count at creation
  count = 99;
  return staleHandler;
}

// Ref approach — always reads latest
function makeRefHandler(ref) {
  return () => ref.current * 2;  // reads .current at call time
}

const stale = makeStaleHandler(5);
const ref = { current: 5 };
const fresh = makeRefHandler(ref);

ref.current = 99;

console.log(stale());
console.log(fresh());

Correct Output

198
198

Why this output?

Explanation: Both return 198 here because both close over the same final value. But the stale version only works because count changed BEFORE the closure was captured in this test. In React, stale closures capture state at render time.

Key Insight: A ref's .current is always the latest value because you're reading a property of a stable object. A state variable in a closure is frozen at the render it was created in.

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz