Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is useEffect executed only once when multiple states in the useEffect dependency array change at once?

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading