JavaScript React by Example Building the Application Adding Guests to the List

Anthony Albertorio
Anthony Albertorio
22,168 Points

React Docs now recommends using function with prevState inside of setState

From what I understand, React recommends using a function inside of setState that takes in prevState and an optional props parameter.

According to the React docs "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."

"To fix it, use a second form of setState() that accepts a function rather than an 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:"

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

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

// es5 way
// Correct
this.setState(function(prevState, props) {
  return {
    counter: prevState.counter + props.increment
  };
});

See the React docs for more information: https://reactjs.org/docs/state-and-lifecycle.html

Also, see this great post: https://medium.com/@shopsifter/using-a-function-in-setstate-instead-of-an-object-1f5cfd6e55d1

A better way could be by just updating the new state like this:

class App extends Component {
//...

  newGuestSubmitHandler = e => {
    e.preventDefault();
    if (this.state.pendingGuest !== "") {
      const newPerson = {
        name: this.state.pendingGuest,
        isConfirmed: false,
        isEditing: false
      };
      this.setState(prevState => ({
        guests: [newPerson, ...prevState.guests],
        pendingGuest: ""
      }));
    }
  }

//...
}
Young Bae
Young Bae
18,429 Points

Good to know! It helps me a lot :) Thank you for posting.

1 Answer

nice to see other ways of doing stuff or thinking.