I was learning React and came across this question Why is setState in reactjs Async instead of Sync? and someone called "Sachin" answered that setState() is not web api. Then, I asked myself if it is not web api but asynchronous, how is it actually run? That is, if something is called asynchrounsly then it is logical that it is run via callback so as not to block the main stack. So, the question is if setState() is not web api, how is it called asynchronously?
Asked
Active
Viewed 103 times
0
-
If you read the entire answer of "Sachin", you have your answer – Jonathan Hamel Feb 24 '20 at 14:03
-
@JonathanHamel, I did but couldn't get it properly, please can you kindly clarify? – MII Feb 24 '20 at 14:24
-
`setState` isn't *called* asynchronously, it's *run* asynchronously. There are a number of reasons for this (e.g., batching, avoiding re-renders). The implementing code is somewhat complex; there's a walk-through https://github.com/numbbbbb/read-react-source-code/blob/master/03-how-setstate-works-part-1.md, https://github.com/numbbbbb/read-react-source-code/blob/master/03-how-setstate-works-part-2.md, and https://github.com/numbbbbb/read-react-source-code/blob/master/05-how-setstate-works-part-3.md. – Dave Newton Feb 24 '20 at 16:59
-
@DaveNewton, thank you Dave for your kind comments :) – MII Feb 25 '20 at 06:38
1 Answers
1
I think your problem is not setState
but the meaning of the word asynchronous. The word asynchronous literally means: not existing or occurring at the same time.
Let's say we have this pseudo code:
fnOne()
fnTwo() // this is async
fnThree()
The flow of execution of our pseudo code would be fnOne
, fnThree
, fnTwo
. Because fnTwo
is async, it is not happening at the same time as fnOne
and fnThree
. It is happening later.
To answer your question about setState
. You call it but React doesn't go and update the state, run the diff algorithm, and replace the DOM, at the moment of the call. React does all of that eventually, at a later time, asynchronously.

Johnny Zabala
- 2,285
- 1
- 12
- 14