Potentially inconsistent state updateΒΆ
ID: js/react/inconsistent-state-update
Kind: problem
Security severity:
Severity: warning
Precision: very-high
Tags:
- reliability
- frameworks/react
Query suites:
- javascript-security-and-quality.qls
Click to see the query in the CodeQL repository
React component state updates using setState may asynchronously update this.props and this.state, thus it is not safe to use either of the two when calculating the new state passed to setState.
RecommendationΒΆ
Use the callback-based variant of setState: instead of calculating the new state directly and passing it to setState, pass a callback function that calculates the new state when the update is about to be performed.
ExampleΒΆ
The following example uses setState to update the counter property of this.state, relying on the current (potentially stale) value of that property:
this.setState({
counter: this.state.counter + 1
});
Instead, the callback form of setState should be used:
this.setState(prevState => ({
counter: prevState.counter + 1
}));
ReferencesΒΆ
React Quick Start: State and Lifecycle.