Search code examples
javascriptreactjscreate-react-app

React setState syntax


My question is pretty straight forward, I've found the state being updated in a few places like this and am wondering why would we use this syntax:

const showFlagRev = this.state.showFlag;
this.setState({showFlag: !showFlagRev});

Over this syntax:

this.setState(prevState => ({showFlag: !prevState.showFlagRev}));

Is there any reason to this or is this just a old (maybe clearer?) way of update the state in a React application?

Any references (docs, articles, examples) are much appreciated!


Solution

  • From the docs:

    This form of setState() is also asynchronous, and multiple calls during the same cycle may be batched together. For example, if you attempt to increment an item quantity more than once in the same cycle, that will result in the equivalent of:

    Object.assign(
      previousState,
      {quantity: state.quantity + 1},
      {quantity: state.quantity + 1},
      ...
    )
    

    Subsequent calls will override values from previous calls in the same cycle, so the quantity will only be incremented once. If the next state depends on the current state, we recommend using the updater function form, instead:

    this.setState((state) => {
      return {quantity: state.quantity + 1};
    });