Predict state snapshots and updater queues
Read the state from this render
A handler closes over the values available when its component was rendered. Calling a setter does not change those captured values. You can calculate a next value before requesting the update if you also need it in the current handler.
import { useState } from 'react';
export default function App() { const [packed, setPacked] = useState(4); function packTwo() { const next = packed + 2; setPacked(next); console.log('Before:', packed, 'Requested:', next); } return <main><h1>Batch packing</h1><p role="status">Packed: {packed}</p> <button type="button" onClick={packTwo}>Pack two</button> </main>;}First activation logs Before: 4 Requested: 6. The display is expected to become Packed: 6 after the update commits. Another activation logs Before: 6 Requested: 8. The setter returns no result to await; reading packed immediately after it still reads the current handler’s value.
Combine pending updates correctly
import { useState } from 'react';
export default function App() { const [packed, setPacked] = useState(4); function replaceTwice() { setPacked(packed + 2); setPacked(packed + 2); } function addTwice() { setPacked(previous => previous + 2); setPacked(previous => previous + 2); } return <main><h1>Batch packing</h1><p role="status">Packed: {packed}</p> <button type="button" onClick={replaceTwice}>Two replacements</button> <button type="button" onClick={addTwice}>Two increments</button> <button type="button" onClick={() => setPacked(4)}>Reset</button> </main>;}From 4, Two replacements requests 6 twice and ends at 6. Reset, then Two increments calculates 4 to 6 to 8. React batches ordinary synchronous event updates rather than committing each intermediate value. Do not infer an exact number of component calls or assume all independent events are combined. Use a function when the result depends on pending state.
Mix replacement and updater requests
import { useState } from 'react';
export default function App() { const [packed, setPacked] = useState(4); function startBatch() { setPacked(10); setPacked(previous => previous + 2); } return <main><h1>New batch</h1><p role="status">Packed: {packed}</p> <button type="button" onClick={startBatch}>Start with sample</button> </main>;}The queued replacement establishes 10, and the next function receives 10 and returns 12. Repeating the action still requests 12. React uses Object.is to compare the resulting state with the current state and may skip unnecessary rendering work; do not rely on an exact call count. Keep updater functions pure: no logging, network requests or mutation within them. Development StrictMode can invoke an updater twice to detect impurity, ignoring one result.
Practice
Starting with 5, predict the final value for each independent sequence: replace with 9 then subtract 2 using an updater; add 3 using an updater then replace with 9; two updater functions each adding 3. Explain why the sequences differ.