-
- Notifications
You must be signed in to change notification settings - Fork 2.8k
Closed
Description
When using previous state in setState it can be unsafe to use this.state, because the scheduling and batching in react might result in this.state
being something else than when the function was called. This might lead to race condition like a counter being set to 1, 2, 3, 3
if the two last calls are called within a batch when the expected result would be 1, 2, 3, 4
.
Example
// Good this.setState((previousState) => ({ counter: previousState.counter + 1 })); // Bad this.setState({counter: this.state.counter + 1});
I am currently working on implementing a rule like that enforces using callback pattern if state is accessed within setState. Is this something that you would like to have in this plugin?
tleunen, gmathieu, adnasa, Kepro, andrewrota and 6 more