React
Cleanup function
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.
Exercise 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.
Show example solution
import { useEffect } from "react";
function Timer() {
useEffect(() => {
const id = setInterval(() => {}, 1000);
return () => clearInterval(id);
}, []);
return <p>Timer</p>;
}
export default Timer;
Test yourself
-
When is the cleanup function called?
Cleanup releases the resource.
- Before the effect re-runs and on unmount
- Only on error
- When the effect starts
- Never
Show answer
Before the effect re-runs and on unmount — Cleanup runs before the effect and when the component leaves.
-
Cleanup function: fill in the missing part
useEffect(() => { const id = setInterval(fn, 1000); return ____; }, []);
Show answer
useEffect(() => { const id = setInterval(fn, 1000); return () => clearInterval(id); }, []);
-
Cleanup function: match the terms
- return () => ...
- Cleanup
- clearInterval
- Stop a timer
- removeEventListener
- Remove a subscription
- unmount
- Component leaves
Next lesson: Summary - useEffect