Unmount
- React Native course
- Intermediate
- Lesson 61/116
- 5 min
Learn the component unmount event.
Unmount
A component unmounts when it is removed from the screen. This is the end of its lifecycle. React disposes the component and releases its event listeners and subscriptions.
To clean up on unmount, useEffect returns a cleanup function. This function runs right before the component is removed, or before the next effect run.
Using cleanup
If you set up a setInterval or addEventListener, you must clean it up. The cleanup returned by the useEffect function releases the resource.
Example: useEffect(() => { const id = setInterval(tick, 1000); return () => clearInterval(id); }, []). The timer starts on mount and is cleared on unmount. This prevents memory leaks.
Practice Set up and clear a timer
Set up a setInterval and call clearInterval as cleanup. The timer should be cleared when the component is removed.
Starter code
import React, { useState } from 'react';
import { Text } from 'react-native';
export default function Clock() {
const [tick, setTick] = useState(0);
// Set up setInterval on mount, call clearInterval on unmount
return <Text>{tick}</Text>;
}Sample solution
import React, { useState, useEffect } from 'react';
import { Text } from 'react-native';
export default function Clock() {
const [tick, setTick] = useState(0);
useEffect(() => {
const id = setInterval(() => setTick(t => t + 1), 1000);
return () => clearInterval(id);
}, []);
return <Text>{tick}</Text>;
}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?
- Right before the component is removed Correct answer
- Only during mount
- Never
- Only on a style change
Explanation: Cleanup runs right before unmount.
2 Unmount concepts
| Term | Meaning |
|---|---|
unmount |
Removal moment |
cleanup |
Cleanup function |
return |
Returns cleanup |
subscription |
Released |
3 Return cleanup
useEffect(() => { const id = setInterval(tick, 1000); ____ }, []);
useEffect(() => { const id = setInterval(tick, 1000); return () => clearInterval(id); }, []);
Explanation: The cleanup clears the timer on unmount.