React setState

Use setState instead of changing state directly in React. Here’s how setState is used.

1 setState is synchronous or asynchronous

  • Asynchronous in a synthetic event or lifecycle
  • This is synchronized with setTimeout or with native event and setState callbacks
<button onClick={this.setCounter}>{counter}</button>



setCounter = () => {

  this.changeValue(1)

}

changeValue = (v) => {

  this.setState({

    counter: this.state.counter + v

  })

  console.log(this.state.counter)

}

Copy the code

Print counter is always 1 less than it really is. Because setState is executed asynchronously in a synthesized event. The same is true in the life cycle

The following are synchronized events:

setTimeout:

setCounter = (a)= > {

  setTimeout((a)= > {

    this.changeValue(1)

  },0)

  console.log(this.state.counter)

}

Copy the code

Native events:

<button id="test"> native event {counter}</button>



doucument.getElementById('test').addEventListener('click', this.setCounter)

Copy the code

SteState callback event, which is performed after the state update

this.setState({

  counterthis.state.counter + v

},

() = > {

  console.log(this.state.counter)

)

Copy the code

All the above three are synchronous, and the printed counter is accurate after execution

2 State Batch update

State is updated in batches. The reason is to optimize performance. Multiple states are updated in batches. Such as:

this.changeValue(1)

this.changeValue(2)

Copy the code

In this case only changeValue(2) is actually executed

To make a chain call, you need to receive a function

this.setState(state= > {

  return {

    counterthis.state.counter + v

  }

})

Copy the code