1. SetState and useState are “asynchronous” only in synthesized events and hook functions, synchronous in native events and setTimeout, promise.resolve ().then.

  • A. React Synthesizes events, such as onClick

  • B. Hook functions include componentDidMount, useEffect, etc

2, “asynchronous” does not mean that the internal implementation of asynchronous code, in fact, the execution of the process and code are synchronous, but the order of the synthesis event and hook function call before the update, so in the synthesis event and hook function can not get the updated value immediately, the so-called “asynchronous” form.

3. Batch update optimization is also based on “asynchronous” (composite events, hook functions). Batch updates are not performed in native events and setTimeout, promise.resolve ().then. Assin is similar to Object. Assin. If the value of multiple different variables is changed at the same time, for example, the value of A is changed and the value of B is changed, the combined batch update will be performed during the update, resulting in only one render.

4. SetTimeout, promise.resolve ().then in composite events and hook functions are executed after the “asynchronous” update state is executed and the component is rendered.

Example:

Console print result: