A React interface is recomputed from a render's state snapshot. A setter schedules work; it does not rewrite a local variable captured by the handler that is already running. Keys determine which sibling identity React can preserve, while Effects synchronize committed UI with something outside React. Confusing any of these timelines can make correct-looking code behave unexpectedly.
Replacement values and updater functions
Consider one synchronous event handler from a committed render where n is 3. Both setN(n+1) expressions evaluate using that handler's captured 3; each enqueues a replacement value 4. Applying two replacements gives 4, not 5. In contrast, setN(v => v+1) enqueues an instruction. React applies it to the pending value, and a second updater receives the first updater's result. Two such increments take 3 to 5. The handler's local n is still 3 after the calls; a later render receives the resulting state.
Definition 6.2.1
(Replacement value and updater function)
A value passed directly to a state setter, as in setN(4), is a replacement: it discards the pending state and supplies the next one. A function passed to the setter, as in setN(v => v + 1), is an updater function: React calls it with the pending state produced by the earlier updates in the queue and uses its return value as the new pending state.
An updater should be pure: it describes a state transition without modifying external state or mutating the previous value. In development Strict Mode React may invoke updater functions twice to detect impurity; the result of one invocation is ignored. This check is not permission to rely on the updater running exactly once for a side effect. A network write or log that must happen once for an action belongs in appropriately designed event or external-system logic, not inside the updater.
Common mistake
(Reading the state variable right after the setter)
After setN(n + 1) a handler that goes on to call save(n) sends the old value. If n was 3, the queued replacement is 4, but the handler's n is still 3, so save receives 3. Compute the next value once, as in const next = n + 1;, then use next both for setN(next) and for save(next). Reading n after the setter describes the render that is finishing, not the state that will be rendered next.
Worked problem: a mixed queue
Worked example 6.2.2
(A mixed queue)
From a render where n=3, one handler calls, in order:
setN(n + 2);
setN(v => v * 2);
setN(n - 1);
setN(v => v + 4);
Assuming these updates are processed in this order for the same state, the first replacement is 5, the updater makes 10, the next replacement is 2 because it was computed from the original snapshot 3, and the last updater makes 6. The next resulting state is 6. A console.log(n) later in that same handler still logs 3. The example is about the queue's values and order, not a claim that arbitrary separate events or every asynchronous update are one indivisible transaction.
Concept lensAlgebraic
A queue as a composition of functions
Treat each setter call as a function on states: setN(4) is the constant function sending every state to , and setN(v => v + 4) is . The next state is these functions composed in order, applied to the render's state. For the queue above: . Two updaters send to , while two replacements of send to .
Copy the changed path, not just the outer name
State arrays and objects are references. Suppose items contains records A and B, and only B's done must change. A functional update can map the previous array, returning a new B object with the toggled value while returning the unchanged A object. This creates a new outer array and preserves the old snapshot. Copying only the outer array and then mutating the shared B record would still mutate the earlier snapshot; setting the same array reference after mutation can also cause React to skip an update by identity.
The point is not that every nested object must be copied on every update. Copy each container along the path whose content changes, and reuse unchanged objects when their identity remains valid. If state is deeply nested or duplicated in several places, a flatter representation or a single owner can reduce the number of paths that must agree. Props are read-only inputs: a child requests a change through a callback rather than modifying a parent's record.
Keys identify siblings in a position-sensitive tree
React associates state with a component's position and identity in the rendered tree. Keys distinguish siblings during reconciliation; a stable data ID lets an item retain the intended identity when a preceding item is removed or the list is reordered. Keys are not ordinary props: pass the ID separately if the child needs to read it. Keys need only be unique among the relevant siblings. A new random key on every render requests a new identity and can reset local state. A stable key does not preserve state after a component is genuinely unmounted and later mounted again; lifting state to a common owner is one way to preserve a draft across that absence.
Worked problem: removing the first row
Worked example 6.2.3
(Removing the first row)
Rows A, B and C each contain a child-owned draft.
| Key scheme | Before removal (key: record) | After removing A |
|---|---|---|
| array index | 0: A, 1: B, 2: C | 0: B, 1: C |
| stable record ID | A: A, B: B, C: C | B: B, C: C |
Initially index keys 0,1,2 are attached to A,B,C. After A is removed, B is rendered at index key 0 and C at key 1. React can reuse the component previously associated with key 0 for B, so A's draft may appear beside B. With stable keys A,B,C, the B and C identities remain associated with their records after removal. If a filter removes B from the tree and later restores it, B's former child-local state need not survive that unmount: preserve it in the parent keyed by B's ID if that behavior is required. Stable keys solve matching among present siblings, not persistence across every lifecycle change.
An Effect owns a setup–cleanup pair
Rendering calculates a description; it should not start a timer or open a connection as a side effect of rendering. An Effect synchronizes a committed component with an external system. Its setup may subscribe or start a timer; its cleanup should undo precisely that setup. When dependencies change, React runs the old cleanup before setting up synchronization for the new dependencies, and runs cleanup when the component is removed. The dependency list reflects the reactive values the Effect reads; it is not merely a performance preference.
Worked problem: a changing subscription
Worked example 6.2.4
(A changing subscription)
The committed renders and their Effect calls are:
- Mount with
roomIdA: setup subscribes A. - Commit with
roomIdB: the previous cleanup unsubscribes A, then setup subscribes B. - Removal: the cleanup of the B setup unsubscribes B.
A component subscribes to room A in an Effect whose dependency is roomId and returns a function that unsubscribes that same room. On a committed change from A to B, the expected sequence is unsubscribe A, then subscribe B. On removal, unsubscribe B. If cleanup instead reads a mutable global “current room,” it might unsubscribe B while leaving A active. Capture the resource created by each setup and close that resource in its own cleanup. An empty dependency list would not re-synchronize when the room prop changes, and omitting the dependency argument runs the Effect after every committed render rather than only on room changes.
With root Strict Mode in development, React performs an extra setup–cleanup–setup check on initial mount. Correct cleanup leaves one active subscription after that check, not two. This is a development stress test; it does not mean every production update must execute the identical sequence. Some work is triggered by a particular click rather than by the component being visible; do not move every event into an Effect simply to make it run later.
Counterexample mode
An empty dependency list does not mean connect once correctly
Claim: for an Effect that connects to roomId, the dependency list [] is right because the connection should be made only once. Trace it. On mount with roomId equal to general, setup connects general. The room then changes to travel and the component re-renders. React compares the dependency list [] with the previous [], finds no difference, and runs neither cleanup nor setup. The screen now says travel, yet the only open connection is still to general; on removal the cleanup disconnects general, and travel was never connected at all. The Effect reads roomId, so [roomId] is the accurate list: the trace then becomes connect general, disconnect general, connect travel, disconnect travel.
A practical reasoning order
First identify which render produced the handler and what its captured values were. Then write the queued replacement values and updater functions in order. Next determine which data identity belongs to each keyed sibling and whether a component remained mounted. Finally pair each Effect setup with the cleanup of the exact resource it created. These four questions explain state behavior without treating a render, an event and an external subscription as one simultaneous action.
Timer closures and cleanup are separate concerns
Suppose a component renders with count=0 and installs one interval in an Effect with an empty dependency list. Its callback contains setCount(count + 1). The callback closes over the value from the render that installed it. Each tick therefore requests replacement by 1; a later tick does not automatically see the new render's count inside that old closure. Changing the callback to setCount(v => v + 1) makes each tick express an increment of the pending state. It does not, by itself, cancel the interval on removal: setup must still return cleanup that clears the exact interval ID.
Worked problem: account for the interval lifecycle
Assume the fixed updater starts from 0 and three timer callbacks are processed in order, with no other updates. The displayed state eventually reaches 3. If instead the callback used the captured count + 1, each callback would request 1 and the result would remain 1. On unmount, a correct cleanup calls clearInterval with the ID returned by that Effect's own setup. In root Strict Mode development, the initial setup–cleanup–setup sequence creates an interval, clears it and creates a replacement; after the check one is active. Omitting cleanup could leave two active intervals and make ticks appear doubled. Browser throttling means neither example is a wall-clock accuracy guarantee.
If an Effect genuinely reads a changing roomId, putting an empty dependency array on it to avoid reconnecting is not a correctness fix: it keeps synchronizing the old room. Put the required reactive value in the dependency list and make cleanup undo the connection created by that setup. If a value can be computed directly from props or state during rendering, storing a second copy and using an Effect to keep it synchronized can create an avoidable stale intermediate state. Effects are for synchronization with an external system; a pure derived value usually does not need one.
Worked problem: identity depends on type and position too
Suppose a parent first renders <Editor key="A" />, then in the same tree position renders <Preview key="A" />. The matching key does not turn two different component types into the same component; the editor is removed and its local state does not transfer to the preview. Conversely, rendering the same keyed Editor again at the matching sibling position can preserve its local state even if its props have changed. A key is scoped among siblings, not a global database identity, and React may reset state when the element type or tree position changes. To preserve a draft across a genuine removal or type change, put it in an owner that remains mounted, or explicitly persist it elsewhere under a stable record ID.
This is why a result can be correct for a queue trace yet still wrong for a list trace: one question asks how values are reduced, the other asks which component identity receives the value. Check both before debugging effects or rendering performance.
Practice
Quick check
(Two replacements and an updater)
From a render where n is 1, one handler calls setN(n + 1), setN(n + 1) and then setN(v => v * 3). What is the next state, and what does console.log(n) print if it runs after these calls in the same handler?
Solution
Both replacements are computed from the captured value 1, so each supplies 2; after them the pending state is 2. The updater receives that pending state and returns 6, so the next state is 6. The log prints 1, because the handler's n belongs to the render that created the handler and is not reassigned by the setter calls.
Quick check
(Toggle one record without mutation)
State items holds [{ id: "a", done: false }, { id: "b", done: false }]. Write a functional update that toggles done for b, and say which objects in the new state are new and which are reused.
Solution
One correct update is setItems(prev => prev.map(item => item.id === "b" ? { ...item, done: !item.done } : item)). The outer array is new, the b record is a new object with done: true, and the a record is the same object as before, because its content did not change. Writing prev[1].done = true and then calling setItems(prev) would mutate the earlier snapshot and pass the same array reference, so React may skip the update.
Quick check
(Index keys after inserting at the front)
Rows B and C each hold a typed draft in child-owned state and are rendered with index keys. A new row A is inserted at the front. Which draft is shown beside each of A, B and C after the update?
Solution
After the insertion A has key 0, B has key 1 and C has key 2. React reuses the component that had key 0, so B's draft appears beside A; the component with key 1 keeps C's draft and now shows it beside B; key 2 is new, so C is mounted with an empty draft. Using each record's stable ID as its key keeps every draft with its own record.
Quick check
(Pair each setup with its cleanup)
An Effect with dependency list [roomId] runs const connection = createConnection(roomId); connection.connect(); and returns () => connection.disconnect(). In production, roomId changes from general to travel, and then the component is removed. List the connection calls in order.
Solution
The calls are: connect general; disconnect general; connect travel; disconnect travel. Each cleanup closes the connection object created by its own setup, so the old room is always disconnected before the new one is connected. In development with root Strict Mode, the initial mount adds one extra connect and disconnect of general before the final connect; one connection is still active afterwards.
Quick check
(Repair a stale interval)
An Effect with an empty dependency list runs setInterval(() => setCount(count + 1), 1000) and returns nothing. Identify two defects and give a corrected Effect body.
Solution
First, the callback captures count from the render that installed it, so every tick requests the replacement 1 and the display stops at 1. Second, nothing clears the interval, so it keeps running after removal, and the development Strict Mode check leaves two intervals active. A corrected body is const id = setInterval(() => setCount(c => c + 1), 1000); return () => clearInterval(id);. Because the Effect no longer reads count, the empty dependency list is now accurate.