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

后端 未结 2 1141
我寻月下人不归
我寻月下人不归 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条回答
  • 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!

    0 讨论(0)
  • 2021-02-14 12:10

    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> ); 
    }; 
    
    0 讨论(0)
提交回复
热议问题