There are some gotchas with React’s setState()
. For example, state updates may be asynchronous: React sometimes batches multiple setState()
calls for performance reasons.
Make sure to set state correctly and to use the latest state. Here are some examples from the official documentation:
// Wrong
this.setState({
counter: this.state.counter + this.props.increment
});
Instead you should use a function which takes the previous state as a first argument.
// Correct
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
Let’s say you have an object in your state and want to use the object spread syntax:
// This is the state of your React component
this.state = {
person: {
firstName: "",
secondName: ""
}
};
Now you want to change the state:
this.setState(prevState => ({
person: {
...prevState.person,
firstName: "Tom",
secondName: "Jerry"
}
}));
This also works:
this.setState(() => ({
person: {
...this.state.person,
firstName: "Tom",
secondName: "Jerry"
}
}));
Using functions is now the recommended way to set state in React.