When Cleanup Runs: On Unmount
You'll learn the final moment when your cleanup function executes: when the component is removed from the screen entirely.
The Final Cleanup
You already know that cleanup runs before an effect re-runs. But there's one more critical moment: when the component unmounts (gets removed from the DOM completely).
This is your last chance to clean up resources, cancel subscriptions, remove event listeners, or abort ongoing operations. If you don't clean up here, those resources may leak and continue running even after your component is gone.
Why This Matters
Imagine you set up a timer or subscribe to a data stream in your effect. If the user navigates away and your component unmounts, that timer keeps ticking or that subscription keeps listening. This wastes memory and can cause errors when callbacks try to update state in a component that no longer exists.
The cleanup function is your safety net: React guarantees it will run when the component unmounts, giving you a chance to tear down everything you set up.
The Analogy
Think of renting an apartment. When you move in (mount), you set up utilities and subscribe to internet. When you move out (unmount), you must cancel those services. The cleanup function is like your move-out checklist—it ensures nothing keeps running or charging you after you've left.
The Lifecycle
- Component mounts → effect runs
- Dependencies change → cleanup runs, then effect re-runs
- Component unmounts → cleanup runs one final time
That final cleanup on unmount is non-negotiable. React always calls it, ensuring your component leaves no trace behind.
Key Takeaway: Cleanup always runs when your component unmounts, making it the perfect place to free resources, remove listeners, and prevent memory leaks before the component disappears.