Cleanup
- React Native course
- Intermediate
- Lesson 3/116
- 5 min
Learn the useEffect cleanup function.
What is cleanup?
The function returned by useEffect is called cleanup. It runs right before the component is removed from screen (unmount). It is used to cancel subscriptions, clear timers or remove event listeners.
Cleanup also runs once before each effect re-run. This lets you release the old resource and set up a new one. If you skip cleanup, you can get subscription buildup (memory leak). You write it by returning return () => { /* ... */ } from the effect.
Cleanup examples
A typical cleanup example is a timer. You start a setInterval inside the effect and stop it with clearInterval in the returned function. So when the component is removed the timer does not keep running in the background.
A second example is an event listener. You add a listener with addEventListener and remove it with removeEventListener in cleanup. Without cleanup the listener keeps catching events even after the component is gone, which is unwanted.
Practice Write a timer cleanup
Write a Timer component. Inside useEffect start a setInterval(() => console.log("ticking"), 1000). Return a cleanup function from the effect that calls clearInterval(id). The component returns <Text>Timer</Text>.
Starter code
// Import useEffect
function Timer() {
// Start setInterval inside useEffect; return cleanup
return <Text>Timer</Text>;
}Sample solution
import { useEffect } from "react";
import { Text } from "react-native";
function Timer() {
useEffect(() => {
const id = setInterval(() => console.log("ticking"), 1000);
return () => clearInterval(id);
});
return <Text>Timer</Text>;
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does cleanup run?
| Term | Meaning |
|---|---|
On unmount |
Cleanup is called |
Before re-running the effect |
Old cleanup is called |
Subscription |
Released by cleanup |
Timer |
Cleared with clearInterval |
2 Return the cleanup
useEffect(() => {
const id = setInterval(tick, 1000);
____ () => clearInterval(id);
});
useEffect(() => {
const id = setInterval(tick, 1000);
return () => clearInterval(id);
});
Explanation: Cleanup is returned with return.
3 What is cleanup written for?
useEffect(() => {
const id = setInterval(tick, 1000);
return () => clearInterval(id);
});- To create state
- To style the component
- To release the resource Correct answer
- To add a new effect
Explanation: Cleanup releases the resource.