Home > OS >  Why is useEffect executed only once when multiple states in the useEffect dependency array change at
Why is useEffect executed only once when multiple states in the useEffect dependency array change at

Time:06-09

  <div
    onClick={() => {
      setTest1((x: number) => x   1);
      setTest2((x: number) => x   3); 
    }}
  >
    one? two?
  </div>
  const [test1, setTest1] = useState(1);
  const [test2, setTest2] = useState(1);
  useEffect(() => {
    console.log('!@#$');
    console.log(test1, test2);
  }, [test1, test2]);

Test1 and test2 changed at the same time through onClick, but '!@#$' is printed only once on the console, so even if multiple states change, useEffect seems to be executed only once. I wonder why it is executed only once.

CodePudding user response:

state updates are batched in react for performance. So both of these setStates cause only one rerender. And after that one rerender, useEffect callback is called.

  • Related