When should we use the appropriate way to set state?

briang123

Brian Gaines

Posted on February 17, 2019

When should we use the appropriate way to set state?

I'm still new with React and am trying to understand when we would use each of the, according to React team, correct ways of setting state. I've seen both methods used, but confused when one way would be used over the other.

Why wouldn't we always use Option 2 below?

Here is the link to the React Docs on this section

Do Not Modify State Directly (Option 1)

this.setState({comment: 'Hello'});
Enter fullscreen mode Exit fullscreen mode

State Updates May Be Asynchronous (Option 2)

this.setState((state, props) => ({
  counter: state.counter + props.increment
}));
Enter fullscreen mode Exit fullscreen mode

alt text

💖 💪 🙅 🚩
briang123
Brian Gaines

Posted on February 17, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related