Sub topic 2
Updating React State Safely
Assume you know JavaScript functions, arrow functions, spread syntax, JSX, props, and map and filter. This chapter focuses on state updates that depend on earlier state.
Use updater functions for dependent updates
Each render receives a fixed state snapshot. Calling a setter does not change the snapshot inside the current event handler. When the next value depends on the previous value, pass a function to the setter. React calls that function with the latest pending state.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function addThree() {
setCount(c => c + 1);
setCount(c => c + 1);
setCount(c => c + 1);
}
return <button onClick={addThree}>{count}</button>;
}The parameter c represents the value produced by the preceding update. Three updater functions therefore increase the count by three.
Batching multiple updates
React usually batches state updates from one event handler. It processes them together and then renders the component. This reduces unnecessary renders.
sequenceDiagram
participant H as Event handler
participant Q as Update queue
participant R as React render
H->>Q: setCount(c => c + 1)
H->>Q: setCount(c => c + 1)
Q->>R: Apply both updates
R-->>H: New render with count + 2A value update such as setCount(count + 1) uses the current render's snapshot. Repeating it can enqueue the same value. Use an updater function whenever several updates may depend on one another, including updates from asynchronous callbacks.
Do not mutate state
State should be treated as immutable. Immutability means creating a replacement object or array instead of changing the existing value. Mutation can leave React with the same reference, hide changes, and make updates difficult to reason about.
Updating objects
Use spread syntax to copy existing fields and replace the field that changed:
function ProfileForm() {
const [person, setPerson] = useState({ name: '', email: '' });
function rename(name) {
setPerson(previous => ({ ...previous, name }));
}
return <button onClick={() => rename('Ada')}>{person.name}</button>;
}The updater form is useful when the new object depends on previous state.
Updating arrays
Create a new array for every change:
- Add with
[...items, newItem]. - Change with
map. - Remove with
filter.
Keep a stable id as each rendered item's key. Do not use push, splice, or direct property assignment on state.
Exercise
Why does three calls to setCount(count + 1) often increase the count by only one?
Show answer
All three calls read the same render snapshot. Use setCount(c => c + 1) so each update receives the latest pending value.