What is a closure in JavaScript?
A function updates a counter after its outer function has returned. In React, a timer also remembers a counter, but it keeps reading zero after the UI has updated. How can closures explain both behaviors?
Interview answer
A closure is a function together with access to the lexical environment in which it was created. It can keep using those bindings after the outer function returns. In React, each render creates a new set of bindings. A callback created by an older render can keep reading the state snapshot from that render.
Follow the bindings in plain JavaScript
function makeCounter() {let value = 0;return {increment() { value += 1; },read() { return value; },};}const cart = makeCounter();const inbox = makeCounter();cart.increment();console.log(cart.read()); // 1console.log(inbox.read()); // 0
increment and read from the same call share the same value binding. A second call to makeCounter() creates a separate binding. This is why closures can hold private state. The same principle explains the classic loop bug: callbacks created in a var loop share one function-scoped binding, while a let loop creates a fresh binding for each iteration.
Debug the React version
Suppose the callback below reads count and calls setCount(count + 1). With an empty dependency list, the callback retained by the timer is from the first render. If that render had count === 0, every tick asks React to set it to 1. React renders a new snapshot after the first tick. The old callback still has access to the old snapshot.
import { useEffect, useState } from 'react';export default function Counter() {const [count, setCount] = useState(0);useEffect(() => {const timer = setInterval(() => setCount(current => current + 1), 1000);return () => clearInterval(timer);}, []);return <p>Seconds elapsed: {count}</p>;}
The functional updater computes the next value from the state React supplies. If the effect should restart when a prop changes, include that prop in its dependencies. A ref can hold mutable information for callbacks that need to read a current value without causing a render. A ref alone does not update visible state.
Interview follow-up
What if the timer adds a step prop on every tick? setCount(current => current + step) fixes the captured count because React supplies current. The callback still closes over step. Include step in the effect’s dependencies if changing it should restart the timer. If the timer must keep its cadence, a React version with useEffectEvent can call an Effect Event from the timer callback to read the latest committed step without restarting the interval.
Further reading · ECMAScript function objects · React state snapshots · Using a timer with the latest values
Related React Ecosystem interview topics
Continue with nearby questions from the same topic cluster.