Why is setState in reactjs Async instead of Sync?

后端 未结 7 1395
一生所求
一生所求 2020-11-21 22:58

I have just found that in react this.setState() function in any component is asynchronous or is called after the completion of the function that it was called i

相关标签:
7条回答
  • 2020-11-21 23:41

    1) setState actions are asynchronous and are batched for performance gains. This is explained in the documentation of setState.

    setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.


    2) Why would they make setState async as JS is a single threaded language and this setState is not a WebAPI or server call?

    This is because setState alters the state and causes rerendering. This can be an expensive operation and making it synchronous might leave the browser unresponsive.

    Thus the setState calls are asynchronous as well as batched for better UI experience and performance.

    0 讨论(0)
提交回复
热议问题