简体   繁体   中英

Why React setState can be asynchronous?

I am aware setState can be synchronous or asynchronous:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

Right, and I understand the function executes a few things:

  • Update the actual value in the state
  • Update the virtual and real DOM as needed with the new state values

But what I'm trying to figure out is why this is sometimes synchronous and sometimes asynchronous? What happens behind the scene? Why can't it be always synchronous?

Thanks.

Your state changes may come from many sources (depending on your app) and each state change in the component is scheduled in a queue. So if you do a this.setState() in your component then it waits, allong with all other potential setStates for this component to be resolved. And it might just happen the when you do something like this.setState({ value: this.state.value + 1 }) and expect outcome Then this operation is waiting to be resolved and if during that wait another operation os state change has happened then we will be operating on the newest this.stare.value, leading to unexpected returns. In generall, when I'm dealing with state changes that are based on previous state then I'm changin state this way: this.setState((prevState) => prevState.value + 1) this means I'm pasing the state that I have currently and make modifications according to this remembered state instead of having to rely on this.state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM