React › Effects & Lifecycle
How do you clean up an effect in React, and why is it important?
IntermediateAnswer
If an effect sets up something like a timer, a subscription, or an event listener, you should return a cleanup function from useEffect that removes it. React automatically calls this cleanup function before the effect runs again and when the component is removed from the screen, preventing memory leaks and unexpected behavior.
useEffect(() => {
const timer = setInterval(() => console.log('tick'), 1000);
return () => clearInterval(timer); // cleanup, stops the timer
}, []);Real-world example A live clock component correctly stops its timer when the user navigates away from the page, because it returns a cleanup function that clears the interval, avoiding a hidden timer that keeps running forever in the background.