Search code examples
javascriptreactjssetstate

How does React SetState update state when comparing to a previous state


Given the example below, which is the pattern of passing a function to setState rather than the object-based alternative below it. I'm a little unclear on the mechanics of updating the state this way. Can anyone help clear it up?

submit(){
   this.setState((prevState, props) => {
      return {showForm: !prevState.showForm}
   });
}

less suggested alternative:

submit(){
       this.setState({showForm: !this.state.showForm}
       });
    }

but what is the mechanism that lets it insert new state if its not old state.
I understand that the negated value is used to sort of coerce the state change, but !prevState.showForm, similar to !this.state.showForm seems like terse syntax and I'm unclear on the mechanics.

Is it that: if the state is the same, the value is falsey, so the state isnt updated, but if the state is different the value is truthey and so the state is updated?


Solution

  • If showForm is not in state, it will be !this.state.showForm will equal to !undefined which is true. This way you can toggle between true and false without having an initial value in the state for a certain parameter.

    I would personally have state = { showForm: false }; in the initial state so that your colleagues or you yourself in 6 months can see at a glance what state this component holds.