React batch updates for multiple setState() calls inside useEffect hook

后端 未结 2 1146
我寻月下人不归
我寻月下人不归 2021-02-14 11:47

On this answer by Dan Abramov here on SO, I\'ve found out the following:

Does React keep the order for state updates?

Currently (React 16 and earl

2条回答
  •  猫巷女王i
    2021-02-14 12:01

    Nice question. Here is additional info to complete @FranklinOcean answer.

    Answer for current version of react, which is 16.8.3.

    Based on the following codesandbox:


    Batched setStuff calls:

    • Inline the component function block synchronously (I think it is equivalent to having an effect running before the other effects and without dependencies)
    • In a useEffect block synchronously
    • In a synthetic event handler synchronously (managed by react, such as onClick={handlerFunction})

    Non batched calls that will trigger a re-render each time:

    • Any asynchronous code (promise/async function in any of the above use cases)
    • Non synthetic event (event managed outside react lib)
    • That includes XHR or other networks callbacks

    I'll try re-run the sandbox with future versions of react to see how it goes!

提交回复
热议问题