React setState Is synchronous or asynchronous

  • The output is 0,0,2,3

React internally merges setState() to optimize the batch processing of setState(), and only keeps the last set of the same property, similar to object.assign ().

React setState determines whether to update this.state directly or in an update ue, based on isBatchingUpdates. IsBatchingUpdates default to false, meaning setState will update this.state; However, there is a function called batchedUpdates that changes isBatchingUpdates to true, When React calls the event handler, batchedUpdates will be called to change isBatchingUpdates to true. The setState of the React event handler will not update this.state synchronously. It’s asynchronous.

In combination with the above analysis, setState in the hook function cannot get the updated value immediately, so the first two times output 0. When executing setTimeout, the values of the first two states have been updated. Due to the setState batch update strategy, This.state. val is only valid for the last time, which is 1. In setTimmout, setState is used to get update results synchronously, so setTimeout outputs 2, 3, and the final result is 0, 0, 2, 3.

SetState () can accept a function as well as an object:

The difference between:

Pass object: batch processing, multiple processing of the same variable will be merged into one, and the result of the last processing will prevail.

Transfer functions: Chain calls. React will queue our functions to update state and then call them in sequence, not in a single call. Also, we pass the previous state to each function so that it is more reasonable to update our state. This function takes two parameters prevState and props.

Conclusion:

Asynchronous case:

Event handlers controlled by React, as well as lifecycle functions, behave asynchronously when calling setState. Most development uses React encapsulated events, such as onChange, onClick, onTouchMove, etc. (in composite events) and hook functions. SetState in these event handlers is handled asynchronously.

Synchronization:

Calls to setState in events outside of React control are updated synchronously. For example, setState updates state synchronously for native JS bound events, setTimeout/setInterval, Ajax, promise. Then and other APIs that React doesn’t control.

Principle: determine whether to batchUpdate according to isBatchingUpdates. If the current setState matches the batchUpdate mechanism, it will be executed asynchronously; if it fails to match, it will be executed synchronously.

Reference Address:

Juejin. Cn/post / 684490…

Blog.csdn.net/fesfsefgs/a…