Skip to content

Commit 70fa3c8

Browse files
committed
Add docs for no-access-state-in-setstate
1 parent 2d53aa7 commit 70fa3c8

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ Finally, enable all of the rules that you would like to use. Use [our preset](#
8888
* [react/forbid-elements](docs/rules/forbid-elements.md): Forbid certain elements
8989
* [react/forbid-prop-types](docs/rules/forbid-prop-types.md): Forbid certain propTypes
9090
* [react/forbid-foreign-prop-types](docs/rules/forbid-foreign-prop-types.md): Forbid foreign propTypes
91+
* [react/no-access-state-in-setstate](docs/rules/no-access-state-in-setstate.md): Prevent using this.state inside this.setState
9192
* [react/no-array-index-key](docs/rules/no-array-index-key.md): Prevent using Array index in `key` props
9293
* [react/no-children-prop](docs/rules/no-children-prop.md): Prevent passing children as props
9394
* [react/no-danger](docs/rules/no-danger.md): Prevent usage of dangerous JSX properties
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Prevent using this.state within a this.setState (no-access-state-in-setstate)
2+
3+
This rule should prevent usage of this.state inside setState calls.
4+
Such usage of this.state might result in errors when two state calls is
5+
called in batch and thus referencing old state and not the current
6+
state. An example can be an increment function:
7+
8+
```
9+
function increment() {
10+
this.setState({value: this.state.value + 1});
11+
}
12+
```
13+
14+
If these two setState operations is grouped together in a batch it will
15+
look be something like the following, given that value is 1:
16+
17+
```
18+
setState({value: 1 + 1})
19+
setState({value: 1 + 1})
20+
```
21+
22+
This can be avoided with using callbacks which takes the previous state
23+
as first argument:
24+
25+
```
26+
function increment() {
27+
this.setState(prevState => ({value: prevState.value + 1}));
28+
}
29+
```
30+
31+
Then react will call the argument with the correct and updated state,
32+
even when things happen in batches. And the example above will be
33+
something like:
34+
35+
36+
```
37+
setState({value: 1 + 1})
38+
setState({value: 2 + 1})
39+
```

0 commit comments

Comments
 (0)