Sub topic 5
Updating state from handlers
This chapter explains what happens when an event handler calls a state setter. It covers why the value you read doesn't change right away, how React batches updates, when to use the functional form, and how to update objects and arrays.
It assumes you can write function components and pass props. It also assumes you know useState basics (a value and a setter) and how to attach a handler such as onClick.
State is a snapshot
Each render of a component sees one fixed value of its state. When React renders Counter with count equal to 0, every function created during that render, including your handlers, sees count as 0. This holds until the next render.
Calling a setter does not change the variable in the running handler. It asks React to schedule a new render with a new value.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
console.log(count); // still the value from this render
}
return <button onClick={handleClick}>Count: {count}</button>;
}On the first click, the console prints 0, and the button then shows Count: 1. The 0 is correct. The handler closed over the count from the render that created it.
Batching: one render per event
React collects every setter call made during a handler and applies them together. It then renders once after the handler returns. This is called batching. It avoids showing half-finished intermediate states and keeps rendering cheap. Since React 18, batching also applies to updates made in timeouts, promises, and native listeners, not only inside React handlers.
The flow looks like this:
Why `setCount(count + 1)` twice adds only 1
Because count is a snapshot, both calls below compute the same thing. If count is 0, each call means "replace the state with 1".
function handleClick() {
setCount(count + 1); // replace with 1
setCount(count + 1); // replace with 1
}React queues two requests to set the value to 1. The final result is 1.
Functional updates
To make an update depend on the latest queued value, pass a function instead of a value. This function is called an updater function. React stores it in the queue and calls it during the next render. It receives the pending state and returns the next state.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(c => c + 1);
setCount(c => c + 1);
}
return <button onClick={handleClick}>Count: {count}</button>;
}React processes the queue in order. The first updater receives 0 and returns 1. The second receives 1 and returns 2. Each click now adds 2.
Values and updater functions can be mixed in one handler. React works through the queue in order, as in this table. It assumes the state starts at 0 and the handler runs setNumber(number + 5) followed by setNumber(n => n + 1).
| Queued update | Pending state before | Result |
|---|---|---|
| `number + 5` (evaluates to `5`) | `0` | `5` |
| `n => n + 1` | `5` | `6` |
The rendered value is 6. If you swapped the order, the updater would run first and the replacement value 5 would win.
When to choose which form
- Use a plain value when the new state doesn't depend on the old state, such as
setOpen(false)orsetName(e.target.value). - Use an updater function when the new state is computed from the previous state and more than one update might be queued before the next render.
- Use an updater function when the update runs later, for example after a timeout or a
fetch. The next section shows why.
Updater rules
Updater functions run during rendering, so they must be pure. Compute the next state from the argument and return it. Don't call other setters, fetch data, or mutate anything outside the function. In development, Strict Mode calls updaters twice to expose impure ones.
Stale values in delayed code
A handler's closure holds the snapshot from the render that created it. Delayed code therefore reads old values.
import { useState } from 'react';
function DelayedCounter() {
const [count, setCount] = useState(0);
function handleClick() {
setTimeout(() => {
setCount(count + 1); // uses the count from the click's render
}, 1000);
}
return <button onClick={handleClick}>Count: {count}</button>;
}If you click this button three times within one second, the count ends at 1. All three timeouts captured count as 0. Changing the call to setCount(c => c + 1) makes each timeout add to the latest queued value, and the count ends at 3.
Objects and arrays: replace, don't mutate
React decides whether to re-render by comparing the new state with the old state using Object.is. If they are the same value, React skips the render. Mutating an object in place and passing the same reference to the setter therefore does nothing visible.
import { useState } from 'react';
function ProfileForm() {
const [profile, setProfile] = useState({ name: '', city: '' });
function handleNameChange(e) {
// Wrong: profile.name = e.target.value; setProfile(profile);
setProfile({ ...profile, name: e.target.value });
}
function handleCityChange(e) {
setProfile(p => ({ ...p, city: e.target.value }));
}
return (
<form>
<input value={profile.name} onChange={handleNameChange} />
<input value={profile.city} onChange={handleCityChange} />
</form>
);
}The spread syntax (...profile) copies the existing fields into a new object. The field you list afterward overrides the copied one. The setter does not merge, unlike this.setState in class components. If you leave out the spread, the other fields are lost.
The same rule applies to arrays. Use methods that return new arrays (map, filter, spread). Avoid methods that mutate (push, splice, sort, reverse) on state.
import { useState } from 'react';
function TodoList() {
const [todos, setTodos] = useState([]);
const [text, setText] = useState('');
function handleAdd() {
if (text.trim() === '') return;
setTodos(list => [...list, { id: crypto.randomUUID(), text, done: false }]);
setText('');
}
function handleToggle(id) {
setTodos(list =>
list.map(t => (t.id === id ? { ...t, done: !t.done } : t))
);
}
function handleRemove(id) {
setTodos(list => list.filter(t => t.id !== id));
}
return (
<div>
<input value={text} onChange={e => setText(e.target.value)} />
<button onClick={handleAdd}>Add</button>
<ul>
{todos.map(t => (
<li key={t.id}>
<label>
<input
type="checkbox"
checked={t.done}
onChange={() => handleToggle(t.id)}
/>
{t.text}
</label>
<button onClick={() => handleRemove(t.id)}>Remove</button>
</li>
))}
</ul>
</div>
);
}Only the toggled item is copied in handleToggle. The other items keep their identity.
Reading the new value right away
If you need the next value inside the same handler, compute it in a variable first and use it for both the setter and your other logic.
import { useState } from 'react';
function Quantity({ onChange }) {
const [qty, setQty] = useState(1);
function handleIncrement() {
const next = qty + 1;
setQty(next);
onChange(next); // uses the same value you just queued
}
return <button onClick={handleIncrement}>Quantity: {qty}</button>;
}Don't read qty after calling setQty and expect the new number. Reading it again returns the old snapshot.
Same-value updates and re-renders
If a setter is called with a value equal to the current one (compared with Object.is), React bails out and skips re-rendering the children. React may still call your component function once more before it stops. That is why setCount(count) is cheap, while setItems([...items]) always triggers a render because the array is new, even when its contents match.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| A log right after the setter shows the old value | State is a snapshot | Use a local variable, or log during render |
| Two `setX(x + 1)` calls add only 1 | Both use the same snapshot | Use `setX(x => x + 1)` |
| A mutated object or array doesn't update the UI | Same reference passed to the setter | Create a new object or array |
| Other fields disappear after an update | Setter replaces, not merges | Spread the old object first |
| A delayed callback uses an old value | Closure captured an earlier render | Use an updater function |
| Updater runs twice in development | Strict Mode checks purity | Remove side effects from the updater |
Summary of the working model
- A render's state values are fixed for that render.
- Setter calls in a handler are queued and applied in one render after the handler finishes.
- A value argument means "replace with this". An updater function means "compute from the latest queued state".
- State holding objects and arrays must be replaced with new copies, not mutated.
Exercise
A component has const [score, setScore] = useState(0). A handler runs setScore(score + 1); setScore(s => s + 10); setScore(score + 5); on the first click. What does score equal after the re-render, and why?
Show answer
It equals 5. During the first render, score is 0. The queue is processed in order. score + 1 evaluates to 1, so the state becomes 1. The updater s => s + 10 receives 1 and returns 11. The last call, score + 5, evaluates to 5 using the snapshot, and it replaces the state with 5. Plain values replace the pending state, so the last one wins.
Exercise
This handler is meant to mark one item as done, but the checkbox never changes on screen: function handleToggle(id) { const item = items.find(i => i.id === id); item.done = !item.done; setItems(items); }. Why does it fail, and how would you fix it?
Show answer
It mutates the existing item and passes the same array reference to setItems. React compares the old and new state with Object.is, sees the same array, and skips the render. Fix it by returning new objects: setItems(list => list.map(i => (i.id === id ? { ...i, done: !i.done } : i)));.