[React] Why you should use “prevState” in setState()

In stackoverflow or some other places that talk about React, I noticed that there were lots of code that did:

removeElement(index) {
  this.setState({
    data: this.state.data.filter((_, i) => i !== index)
  });
}

Or something similar by referencing this.state or this.props directly. However, this is discouraged (Source: https://facebook.github.io/react/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous)

React may batch the setState calls and thus, state may be asynchronously updated. Then, our code may fail to update.

Then how should we fix this code?

removeElement(index) {
  this.setState(function(prevState) {
    data: prevState.data.filter((_, i) => i !== index)
  });
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s