+1 vote
in ReactJS by

Why function is preferred over object for setState()?

1 Answer

0 votes
by

React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

This counter example will fail to update as expected:

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
})

The preferred approach is to call setState() with function rather than object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument.

// Correct
this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}))

Related questions

0 votes
asked Oct 21, 2019 in Gradle by SakshiSharma
0 votes
asked Jul 2, 2019 in ReactJS by Venkatshastri
...