Skip to content

Commit

Permalink
Add docs for no-access-state-in-setstate
Browse files Browse the repository at this point in the history
  • Loading branch information
jaaberg committed Aug 15, 2017
1 parent 2d53aa7 commit 70fa3c8
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ Finally, enable all of the rules that you would like to use. Use [our preset](#
* [react/forbid-elements](docs/rules/forbid-elements.md): Forbid certain elements
* [react/forbid-prop-types](docs/rules/forbid-prop-types.md): Forbid certain propTypes
* [react/forbid-foreign-prop-types](docs/rules/forbid-foreign-prop-types.md): Forbid foreign propTypes
* [react/no-access-state-in-setstate](docs/rules/no-access-state-in-setstate.md): Prevent using this.state inside this.setState
* [react/no-array-index-key](docs/rules/no-array-index-key.md): Prevent using Array index in `key` props
* [react/no-children-prop](docs/rules/no-children-prop.md): Prevent passing children as props
* [react/no-danger](docs/rules/no-danger.md): Prevent usage of dangerous JSX properties
Expand Down
39 changes: 39 additions & 0 deletions docs/rules/no-access-state-in-setstate.md
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})
```

0 comments on commit 70fa3c8

Please sign in to comment.