CodeZettaInterview Hub

JavaScript · Closures · Senior · Scenario

What is a stale closure, and how would you diagnose it in an async UI callback?

Short Interview Answer

A callback closes over an old snapshot of state; later renders/updates change state, but the callback still sees the captured values.

Detailed Explanation

Classic example: an event handler or `setInterval` created in a render/effect closes over `count` from that moment. If `count` updates, the timer still logs the old value unless it reads from a ref, re-subscribes when deps change, or uses functional updates. Diagnosis: log values inside the callback vs current store/ref; check effect dependency arrays; inspect whether the listener was recreated. Fixes depend on framework — refs, store subscriptions, or keying effects correctly. The underlying JS issue is immutable capture of binding values at creation time for `const`/`let` (the binding is live, but React state identity is a new value each render and the old closure kept the old one).

Example

function createWatcher(getCount) {
  // prefer reading via getter/ref to avoid stale snapshots
  setInterval(() => console.log(getCount()), 1000);
}

Interview Tip

Even in a pure JS interview, mention UI frameworks — shows production experience.

Common Mistake

Thinking the outer variable somehow 'disconnects'; — the closure is live for the binding, but the value you closed over may be an old immutable snapshot.

Did you know this answer?