componentWillUnmount: Cleanup Before Removal
What you'll learn: How to clean up side effects like timers and subscriptions before a class component disappears from the page.
The Need for Cleanup
In componentDidMount, you often start ongoing processes: timers with setInterval, subscriptions to data sources, or event listeners. When the component is removed from the DOM, these processes don't stop automatically. They'll keep running in the background, wasting resources and potentially causing crashes when they try to update a component that no longer exists.
Analogy: If you check out a library book (componentDidMount), you must return it before leaving town (componentWillUnmount). Forgetting creates penalties.
How componentWillUnmount Works
This lifecycle method runs once, right before React removes the component from the page. It's your last chance to cancel subscriptions, clear timers, and disconnect listeners:
class Timer extends React.Component {
componentDidMount() {
this.timerID = setInterval(() => {
console.log('Tick');
}, 1000);
}
componentWillUnmount() {
// Clean up the timer before component disappears
clearInterval(this.timerID);
}
render() {
return <div>Check console for ticks</div>;
}
}
Without componentWillUnmount, the interval would continue firing even after Timer is removed, causing memory leaks.
Common Cleanup Tasks
- Cancel timers (
clearInterval,clearTimeout) - Remove event listeners added manually
- Unsubscribe from data sources
- Abort ongoing network requests (if possible)
Key Takeaway: componentWillUnmount is your cleanup crew — cancel timers, remove listeners, and unsubscribe from anything started in componentDidMount or componentDidUpdate to prevent memory leaks and errors after the component is gone.