What Cleanup Functions Are
You'll learn: What cleanup functions do and when React runs them.
The Core Idea
A cleanup function is an optional function you can return from a useEffect. React calls this cleanup function before running the effect again (if dependencies changed) and when the component unmounts.
Think of it like setting up and tearing down. If your effect starts something—like a timer, a subscription, or an event listener—the cleanup function is where you stop or remove it.
How It Works
When you return a function from useEffect, React treats it as cleanup:
useEffect(() => {
// Effect runs here
console.log('Effect running');
return () => {
// Cleanup runs here
console.log('Cleaning up');
};
}, []);
React calls your cleanup function:
- Before running the effect again (if dependencies changed and the effect needs to re-run)
- When the component unmounts (leaves the screen)
Why Cleanup Matters
Without cleanup, you can create memory leaks or stale behavior. For example, if you start a timer but never stop it, it keeps running even after the component is gone.
The Lifecycle
Here's the sequence when dependencies change:
- Component re-renders with new dependency values
- React calls your cleanup function (cleaning up the previous effect)
- React runs your effect again with the new values
On unmount, React just calls cleanup—no new effect runs.
Key Takeaway: Cleanup functions are optional return values from effects that let you "undo" what the effect did, running before the next effect and when the component unmounts. Not every effect needs cleanup—only those that start something requiring teardown.