26 lines
1.3 KiB
Plaintext

== Why is this an issue?
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.
[source,javascript,diff-id=1,diff-type=noncompliant]
----
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.
[source,javascript,diff-id=1,diff-type=compliant]
----
function increment() {
this.setState(prevState => ({count: prevState.count + 1}));
}
----
== Resources
=== Documentation
* https://react.dev/reference/react/Component#setstate[React - setState]
* https://react.dev/reference/react/Component#setstate-caveats[React - setState caveats]