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

后端 未结 2 1140
我寻月下人不归
我寻月下人不归 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: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 (  
        

    A: {a}

    B: {b}

    ); };

    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 ( 
        

    A: {a}

    B: {b}

    ); };

提交回复
热议问题