Middle+
Why is a cleanup (return) function needed in useEffect? What happens without it when using setInterval?
sobes.tech AI
Answer from AI
In React, the useEffect hook can return a cleanup function, which is called when the component unmounts or before the effect runs again.
When using setInterval inside useEffect without a cleanup function, the interval will continue to run even after the component unmounts, leading to memory leaks and unwanted side effects.
Example of correct usage:
useEffect(() => {
const intervalId = setInterval(() => {
console.log('Tick');
}, 1000);
return () => {
clearInterval(intervalId); // Cleanup interval on unmount
};
}, []);
Without clearInterval, the interval will keep running in the background, which can cause errors and degrade performance.