Search code examples
javascriptreactjsvirtual-dom

React keep to single setState call?


Supposed that in a function, i always need to set someState, and only need to set someOtherState if condition is true.

Is it preferable to do it like this:

this.setState({ someState });

if (condition) {
  this.setState({ someOtherState });
}

Or this?

if (condition) {
  this.setState({ someState, someOtherState });
} else {
  this.setState({ someState });
}

I know React is optimized such that calling setState in quick succession will usually not result in a re-render. But is that behavior guaranteed or should the code make such assumption?

eg. supposed it works by re-rendering on a fixed time interval, if the first setState get called right before that interval block ends, then the second setState will result in a re-render?


Solution

  • Why don't you use ternary operator? If condition is true, set it to new state. Otherwise, use the old one.

    this.setState(prevState => ({
      someState,
      someOtherState: condition ? newSomeOtherState : prevState.someOtherState
    }))