Audit react this.setState for incorrect use of this.state

Description

React can batch calls to this.setState(), so the base state (this.state) can be replaced and the value become stale before a state update is applied. The correct approach is to use the callback form of this.setState() so that the latest state can be used instead of a potentially stale one. Similarly if props are used to generate the state update, the props as the second argument to the updater callback should be used to guarantee they are up-to-date.

Any code we have that uses the object form of this.setState() and uses this.state or this.props as the basis for the new value should be replaced with the callback form of this.setState((prevState, props) => ...).

To illustrate, imagine each of these state updates are applied twice in a batch, based on state { foo: 0 }:

https://facebook.github.io/react/docs/react-component.html#setstate

Activity

Show:

Details

Assignee

Reporter

Labels

Tested Version/s

Components

Priority

More fields

Created 19 July 2017 at 01:54
Updated 24 July 2017 at 04:23