Why is setState in reactjs Async instead of Sync?

后端 未结 7 1375
一生所求
一生所求 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:32

    I know this question is old, but it has been causing a lot of confusion for many reactjs users for a long time, including me. Recently Dan Abramov (from the react team) just wrote up a great explanation as to why the nature of setState is async:

    https://github.com/facebook/react/issues/11527#issuecomment-360199710

    setState is meant to be asynchronous, and there are a few really good reasons for that in the linked explanation by Dan Abramov. This doesn't mean it will always be asynchronous - it mainly means that you just can't depend on it being synchronous. ReactJS takes into consideration many variables in the scenario that you're changing the state in, to decide when the state should actually be updated and your component rerendered.
    A simple example to demonstrate this, is that if you call setState as a reaction to a user action, then the state will probably be updated immediately (although, again, you can't count on it), so the user won't feel any delay, but if you call setState in reaction to an ajax call response or some other event that isn't triggered by the user, then the state might be updated with a slight delay, since the user won't really feel this delay, and it will improve performance by waiting to batch multiple state updates together and rerender the DOM fewer times.

提交回复
热议问题