React / 41
this.state and setState
Class state is one object. setState merges your changes into it, applies them later in a batch, and has an updater form for building on the previous value.
One state object
import { Component } from "react";
class Profile extends Component {
state = { name: "Asha", likes: 0, open: false };
render() {
const { name, likes } = this.state;
return (
<button onClick={() => this.setState({ likes: likes + 1 })}>
{name} ♥ {likes}
</button>
);
}
}Read with this.state.something (destructuring keeps render tidy). Change with this.setState(...), which tells React "re-render this component and its children with the new state".
1 · setState merges
You only pass the keys you want to change. React shallowly merges them into the existing state, so name and open survive the click above.
Class: merges
{ count: 1, user: "Asha" }{ count: 2, user: "Asha" } ✓ keptHook: replaces
{ count: 1, user: "Asha" }{ count: 2 } user is gone ✗"Shallow" means one level deep. A nested object is replaced, not merged:
// state = { user: { name: "Asha", city: "Pune" } }
this.setState({ user: { name: "Ravi" } }); // city is gone
this.setState({ user: { ...this.state.user, name: "Ravi" } }); // city kept2 · setState is a request, applied later
setState doesn't change this.state on the spot. React queues the change and, at the end of the event, applies all queued changes in one re-render. This is called batching. Since React 18 it happens everywhere: in click handlers, timeouts and promise callbacks alike (before React 18, only inside React event handlers).
So reading this.state right after setState gives you the old value. Try it:
Three setState calls, one click
Try itEach button calls setState three times in one click. Guess the result first.
3 · The updater form
When the next state depends on the previous one, pass a function instead of an object. React calls it with the latest pending state (and current props), and merges what it returns:
this.setState((prevState, props) => ({
count: prevState.count + props.step,
}));Three object calls all read the same stale this.state.count, so you get +1. Three updater calls chain, so you get +3. Updaters must be pure: no side effects, just compute and return.
Running code after the update
setState takes an optional second argument: a callback React calls after the update is committed, meaning the DOM has been updated.
this.setState({ open: true }, () => {
console.log("Now open:", this.state.open); // true
});For most cases, componentDidUpdate (next topic) is the cleaner place for "after the state changed" logic.
Don't
Mutate state directly
this.state.likes = this.state.likes + 1;
// the number changes in memory,
// but nothing re-rendersDo
Ask React with setState
this.setState((prev) => ({
likes: prev.likes + 1,
}));Gotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
