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

别等时光非礼了梦想. 提交于 2021-02-06 19:58:30

问题


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 earlier), only updates inside React event handlers are batched by default. There is an unstable API to force batching outside of event handlers for rare cases when you need it.

He also mentions that in this Github issue:

https://github.com/facebook/react/issues/10231#issuecomment-316644950

In current release, they will be batched together if you are inside a React event handler. React batches all setStates done during a React event handler, and applies them just before exiting its own browser event handler.

But the fact is that this snippet seems to prove that updates for multiple setState calls inside a useEffect() are batched.

QUESTION

Does React also always batch updates for multiple setState() calls inside useEffect ? Where else does it do that ?

NOTE: According to his answers, on next major release (probably v17) React will batch everywhere by default.

SNIPPET: batch updates inside a useEffect() with multiple setState() calls

function App() {

  console.log('Rendering app...');
  
  const [myState,setMyState] = React.useState(0);
  const [booleanState, setBooleanState] = React.useState(false);
  
  console.log('myState: ' + myState);
  console.log('booleanState: ' + booleanState);
  
  React.useEffect(()=>{
    console.log('Inside useEffect...');
    setMyState(1);
    setMyState((prevState) => prevState +1);
    setMyState(3);
    setMyState(4);
    setMyState(5);
    setBooleanState(true);
  },[]);

  return(
    <div>App - Check out my console!</div>
  );
}

ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>

回答1:


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!




回答2:


If state updates happen directly, React will batch your updates.

Batched:

export default () => { 
   const [a, setA] = React.useState(0); 
   const [b, setB] = React.useState(0);

   useEffect(() => {
    setA(1); setB(1);
   },[]);

   return (  
    <div> 
      <p>A: {a}</p> 
      <p>B: {b}</p> 
    </div> ); 
};

Clicking this button will re-render the component only once.

Non-Batched:

export default () => { 
  const [a, setA] = React.useState(0); 
  const [b, setB] = React.useState(0);

   useEffect(() => { 
    setTimeout(() => { setA(1); setB(1); }, 1000); }
   , []);

   return ( 
    <div> 
     <p>A: {a}</p> 
     <p>B: {b}</p> 
    </div> ); 
}; 


来源:https://stackoverflow.com/questions/56885037/react-batch-updates-for-multiple-setstate-calls-inside-useeffect-hook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!