-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add docs for no-access-state-in-setstate
- Loading branch information
Showing
2 changed files
with
40 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
# Prevent using this.state within a this.setState (no-access-state-in-setstate) | ||
|
||
This rule should prevent usage of this.state inside setState calls. | ||
Such usage of this.state might result in errors when two state calls is | ||
called in batch and thus referencing old state and not the current | ||
state. An example can be an increment function: | ||
|
||
``` | ||
function increment() { | ||
this.setState({value: this.state.value + 1}); | ||
} | ||
``` | ||
|
||
If these two setState operations is grouped together in a batch it will | ||
look be something like the following, given that value is 1: | ||
|
||
``` | ||
setState({value: 1 + 1}) | ||
setState({value: 1 + 1}) | ||
``` | ||
|
||
This can be avoided with using callbacks which takes the previous state | ||
as first argument: | ||
|
||
``` | ||
function increment() { | ||
this.setState(prevState => ({value: prevState.value + 1})); | ||
} | ||
``` | ||
|
||
Then react will call the argument with the correct and updated state, | ||
even when things happen in batches. And the example above will be | ||
something like: | ||
|
||
|
||
``` | ||
setState({value: 1 + 1}) | ||
setState({value: 2 + 1}) | ||
``` |