I’m writing a blog post on the async nature of
setState method, also trying to understand this better. Quoting from the docs:
setState()does not immediately mutate
this.statebut creates a pending state transition. Accessing
this.stateafter calling this method can potentially return the existing value.
There is no guarantee of synchronous operation of calls to
setStateand calls may be batched for performance gains.
After stumbling over this post - http://www.bennadel.com/blog/2893-setstate-state-mutation-operation-may-be-synchronous-in-reactjs.htm and putting up together this example (https://github.com/r31gN/react-set-state-test - check index.html), I can conclude that when things run outside of React context,
setState will trigger a sync update (calling render and everything immediately). This can be see in my example for setTimeout, AJAX call and addEventListener.
However, when things run inside React context,
setState will trigger an async action (the onClick example - thus potentially creating issues with state if you refer to it immediately).
I’d like to know if my understanding of this is correct or I am missing something.
Also, after reading a bit through React source code, I understand that actually,
setState is just a simple method. It’s not async. It just calls different updating strategies under the hood, and those may be sync or async, depending on wether React can batch updates or not for performance reasons (if things happen inside React context or not). It this true?