in React JS by

Why function is preferred over object for setState()?

1 Answer

0 votes

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
  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
Click here to read more about React JS
Click here to read more about Insurance

Related questions

0 votes
asked Jul 2, 2019 in React JS by Venkatshastri
0 votes
asked Feb 7, 2020 in JAVA by rajeshsharma
0 votes
0 votes
asked Nov 26, 2019 in React JS by AdilsonLima
0 votes
asked Mar 27, 2020 in Big Data | Hadoop by rajeshsharma
0 votes
asked May 27, 2019 in Data Handling by tempuser