Skip to content

🤯Incredible phenomenon: strange execution order before and after setState #34039

Answered by lovetingyuan
lovetingyuan asked this question in Q&A
Discussion options

You must be logged in to vote

I think I understand the reason now—the callback of setState isn't always invoked "synchronously"(execute immediately).
This is exactly what happens in the case of 132. When execution finishes inside the effect (at this point, 1 and 3 are printed, and the callback is added to the queue, i.e., concurrentQueues), React schedules the queue to be processed, and then 2 gets printed.
However, all of this occurs within a single macrotask, which is why they appear to execute almost simultaneously.

Replies: 3 comments 3 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
2 replies
@lovetingyuan
Comment options

@lovetingyuan
Comment options

Answer selected by lovetingyuan
Comment options

You must be logged in to vote
1 reply
@lovetingyuan
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants