In React, calling setState
is the primary way to update a component’s state. However, calling setState
is often
asynchronous. React batches state updates for performance reasons, which means that when you call setState
, React doesn’t immediately
update the state and trigger a re-render. Instead, it schedules the update for later, and multiple setState
calls within the same event
handler or function may be batched together. This can lead to unexpected behavior if you assume that state updates are immediate. Therefore, you
should not rely on their values for calculating the next state.
function increment() {
this.setState({count: this.state.count + 1}); // Noncompliant
}
To mitigate this, you should use functional updates when the new state depends on the previous state, ensuring that you’re always working with the
latest state. This can be done with a second form of setState
that accepts a function rather than an object.
function increment() {
this.setState(prevState => ({count: prevState.count + 1}));
}