From componentWillUnmount to Effect Cleanup
What you'll learn: How to convert cleanup logic from componentWillUnmount into the cleanup function pattern used by useEffect.
The Class Component Pattern
In class components, componentWillUnmount was your one chance to clean up before a component disappeared—cancel timers, remove event listeners, abort network requests, etc.:
class Timer extends React.Component {
componentDidMount() {
this.interval = setInterval(() => {
console.log('Tick');
}, 1000);
}
componentWillUnmount() {
clearInterval(this.interval); // Cleanup!
}
render() {
return <div>Timer running...</div>;
}
}
The Hook Equivalent
With useEffect, you return a cleanup function from your effect. React will call it when the component unmounts (or before re-running the effect):
function Timer() {
useEffect(() => {
const interval = setInterval(() => {
console.log('Tick');
}, 1000);
return () => {
clearInterval(interval); // Cleanup!
};
}, []); // Empty deps = mount/unmount only
return <div>Timer running...</div>;
}
Why It's Better
Colocation: Your setup and cleanup live together in the same useEffect call, making it obvious what needs cleaning up. In classes, componentDidMount and componentWillUnmount could be dozens of lines apart.
Think of it like a to-do list: "When I start this task (mount), here's what I do. When I finish (unmount), here's how I clean up." The return function is React saying "tell me how to undo what you just did."
Key Takeaway: Replace componentWillUnmount cleanup by returning a function from useEffect—React calls it automatically when tearing down, keeping setup and teardown logic together.