Sub topic 5
Updating State from Handlers
This chapter assumes you know JavaScript arrow functions, basic JSX, props, and the basics of useState. It covers how event handlers change state, why updates are queued, and when to use a functional update.
Handlers call setters
An event handler is the usual place to change state. The handler runs after a user action, and it calls the setter returned by useState. React then re-renders the component with the new value.
import { useState } from 'react';
function LikeButton() {
const [liked, setLiked] = useState(false);
function handleClick() {
setLiked(!liked);
}
return (
<button onClick={handleClick}>
{liked ? 'Liked' : 'Like'}
</button>
);
}Calling setLiked does not change liked inside the running handler. It asks React to render again with a new value.
State is a snapshot
Each render has its own fixed copy of the state. Inside a handler, the variable count keeps the value from the render that created the handler, even after you call the setter.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
setCount(count + 1);
console.log(count);
}
return <button onClick={handleClick}>Count: {count}</button>;
}On the first click, count is 0 in both calls. Both calls ask for 1, so the button shows 1, not 2. The console.log prints 0, the old value.
Functional updates
When the new value depends on the previous one, pass a function to the setter. React calls these functions in order. Each one receives the result of the one before it.
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>;
}Each click now adds 2. By convention, the parameter is named after the state, often its first letter (c for count).
Batching
React batches the updates from one event. It runs the handler to the end, then renders once. This means a handler with several setters causes one re-render, not one per call.
Choosing the update form
| Situation | Use |
|---|---|
| New value does not depend on the old one | `setName('Ada')` |
| New value is computed from the old one | `setCount(c => c + 1)` |
| Several updates to the same state in one handler | Functional updates |
Objects and arrays
React compares state by reference. If you mutate an object and pass the same object back, React may skip the render. Create a new object or array instead.
import { useState } from 'react';
function Profile() {
const [user, setUser] = useState({ name: 'Ada', age: 36 });
function handleBirthday() {
setUser(u => ({ ...u, age: u.age + 1 }));
}
return (
<button onClick={handleBirthday}>
{user.name} is {user.age}
</button>
);
}The spread operator (...u) copies the existing fields, and age replaces one of them. Note the parentheses around the object. Without them, JavaScript reads the braces as a function body.
Common errors
- Writing
onClick={setCount(count + 1)}. This calls the setter during render and causes an infinite loop. Pass a function instead:onClick={() => setCount(c => c + 1)}. - Mutating state with
user.age++oritems.push(x). Copy first, then set. - Expecting
countto change immediately aftersetCount. Use the value you computed, or read state in the next render.
Exercise
A handler runs setCount(count + 1) three times, and count is 0 on the click. What does the button show after the click? What one change makes it show 3?
Show answer
It shows 1, because all three calls use the same snapshot value of count (0) and each asks for 1. Change each call to the functional form, setCount(c => c + 1), so each update builds on the previous result.
Exercise
Why does setUser(u => ({ ...u, age: u.age + 1 })) work, while user.age = user.age + 1; setUser(user) may not update the screen?
Show answer
The second version mutates the existing object and passes the same reference back, so React sees no change and can skip the re-render. The first creates a new object, which React detects as a change.