Cleanup function
- React course
- Beginner
- Lesson 67/84
- 4 min
Learn to clean up with the function an effect returns.
Cleanup function
An effect can return a cleanup function: return () => { ... }. React calls it before the component leaves the screen or before the effect runs again.
This is for removing subscriptions, clearing timers or closing connections. Without cleanup you get memory leaks.
Every effect should clean up the resource it started; this is basic to responsible usage.
Subscription example
When you start an event subscription you remove it with cleanup. Example: window.addEventListener("resize", fn) to start, return () => window.removeEventListener("resize", fn) to clean.
This is the "setup and teardown" pair; every setup needs a teardown. Otherwise the subscription stays open and events keep firing after the component is gone.
This discipline prevents leaks in long-lived apps. Memory leaks most often come from events and timers; cleanup fixes both in one line.
Practice Timer effect
Complete the skeleton. Write a Timer component; import useEffect. Call useEffect; inside write const id = setInterval(() => {}, 1000); and return () => clearInterval(id);; the second argument is []. Return <p>Timer</p>. Export it.
Starter code
import { useEffect } from "react";
// Define Timer hereSample solution
import { useEffect } from "react";
function Timer() {
useEffect(() => {
const id = setInterval(() => {}, 1000);
return () => clearInterval(id);
}, []);
return <p>Timer</p>;
}
export default Timer;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When is the cleanup function called?
Cleanup releases the resource.- Before the effect re-runs and on unmount Correct answer
- Only on error
- When the effect starts
- Never
Explanation: Cleanup runs before the effect and when the component leaves.
2 Cleanup function: fill in the missing part
useEffect(() => { const id = setInterval(fn, 1000); return ____; }, []);
useEffect(() => { const id = setInterval(fn, 1000); return () => clearInterval(id); }, []);
Explanation: You cleaned up the timer.
3 Cleanup function: match the terms
| Term | Meaning |
|---|---|
return () => ... |
Cleanup |
clearInterval |
Stop a timer |
removeEventListener |
Remove a subscription |
unmount |
Component leaves |