Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Anthony Albertorio
Anthony Albertorio
22,169 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.

2 Answers

nice to see other ways of doing stuff or thinking.

Sean Paulson
Sean Paulson
5,403 Points

Now they recommend using hooks in react. Much easier. Ill post my solution using hooks when I finish if anyone is interested.