1
  <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.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
이재현
  • 13
  • 3
  • Does this answer your question? [Does React batch state update functions when using hooks?](https://stackoverflow.com/questions/53048495/does-react-batch-state-update-functions-when-using-hooks) – Patrick Roberts Jun 09 '22 at 05:25
  • I wouldn't *want* an intermediate effect to run - as you say, the two states change *together*. – Bergi Jun 09 '22 at 05:27

1 Answers1

3

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.

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39