Cleanup for Timers
What you'll learn: How to properly cancel timers created with setTimeout or setInterval to prevent memory leaks and stale updates.
When you create a timer inside useEffect using setTimeout or setInterval, it keeps running even if your component unmounts or the effect re-runs. This can cause bugs where timers try to update state on components that no longer exist, or where multiple timers pile up unnecessarily.
The solution is to return a cleanup function that cancels the timer:
useEffect(() => {
const timerId = setTimeout(() => {
console.log('Timer fired!');
}, 3000);
return () => clearTimeout(timerId);
}, []);
For setInterval, you use clearInterval instead:
useEffect(() => {
const intervalId = setInterval(() => {
console.log('Tick');
}, 1000);
return () => clearInterval(intervalId);
}, []);
Why This Matters
Think of it like setting an alarm clock. If you move to a different room (component unmounts), you need to turn off the alarm in the old room. Otherwise, it'll keep ringing with no one there to hear it — or worse, trigger actions in the wrong context.
When dependencies change and the effect re-runs, React calls your cleanup function before running the effect again. This cancels the old timer and creates a fresh one with the new dependency values.
Common Pattern
useEffect(() => {
const timerId = setTimeout(() => {
setMessage('Hello after delay');
}, 2000);
return () => clearTimeout(timerId);
}, []);
Key Takeaway: Always return a cleanup function that calls clearTimeout or clearInterval to cancel timers when your effect re-runs or the component unmounts, preventing memory leaks and stale updates.