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

is cleanup (clearInterval) really needed in this useEffect scenario?

i’ve an effect function set up and was wondering if the cleanup function was really necessary in this scenario.

this is a basic component which just increments the counter every second.

since this useEffect will only run on the initial mount, only one setinterval function will be set up and that will keep functioning as the counter. since the useEffect will never run again, the cleanup function will never even be fired. correct me if i’m wrong.

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

function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const id = setInterval(() => {
      setCount(c => c + 1);
    }, 1000);
    return () => clearInterval(id);
  },[]);

  return <h1>{count}</h1>;
}

another question:

what if there is no second arg in the useEffect. since the state changes, the useEffect will now run as many times. so a new setInterval function is created each time? so it would make sense to include a cleanup function as without it, several setInterval functions would keep running together? Am i right in this regard?

function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const id = setInterval(() => {
      setCount(c => c + 1);
    }, 1000);
    return () => clearInterval(id);
  });   // no dependency array.

  return <h1>{count}</h1>;
}

>Solution :

For the first question:

  1. The clearInterval will be called not only when the useEffect is called again, but while component unmounting, as well.
  2. If you omit the clearInterval call, the timer will still send messages after the component is unmounted and you will get warnings in console. In most practical scenarios this is a question of performance and code purity, but one can imagine when this could cause issues.

For the second question:

Yes.

Find more here

Understanding React’s useEffect cleanup function

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