JavaScript for React Interviews: Stale Closures

Most frontend candidate failures in React interviews stem from misunderstandings of pure JavaScript rather than React APIs. Bugs like stale closures inside `useEffect` or asynchronous callbacks reading outdated state variables are pure JavaScript closure behaviors.

These bridge lessons show how React hooks rely on JavaScript closures, how state batching mirrors microtask scheduling, and how object reference equality affects render memoization. Master the foundation that powers modern UI frameworks.

Many React bugs are JavaScript bugs. A function created during one render closes over that render's props and state, so a callback or effect that runs later can read values that are already out of date. This is the stale closure problem, and it is behind most interview questions about intervals, event listeners and debounced handlers in React.

The lesson traces it from plain JavaScript closures to useEffect and useCallback, and shows the fixes: correct dependency arrays, functional state updates, and refs that always hold the latest value.

JavaScript for React Interviews: 1 lessons

Frequently asked questions

What is a stale closure in React?

A function that captured props or state from an earlier render and still uses them after newer values exist. A classic case is a setInterval callback created in an effect with an empty dependency array, which always sees the initial count.

How do you fix a stale closure in useEffect?

Add the values the effect reads to its dependency array, use the functional form of the state setter so you do not need the current value, or keep the latest value in a ref that the long-lived callback reads.