Memory leaks
- React Native course
- Expert
- Lesson 11/47
- 5 min
Learn memory leak detection and prevention.
Memory leak
A memory leak is when unused objects are not cleaned from memory. In React Native the most common causes are uncleaned setInterval, removed subscriptions and stray setTimeout.
When a component unmounts, all side effects must be cleaned. useEffect returns a cleanup function that clears timers and subscriptions. Otherwise the component stays in memory even after unmount.
Cleaning subscriptions
Event subscriptions, native module subscriptions and WebSocket connections must be removed on unmount. Otherwise the old component keeps receiving events; this is both a memory and a behavior bug.
Example: DeviceEventEmitter.addListener returns a subscription. Inside useEffect you call subscription.remove(). The same rule applies to NetInfo.addEventListener.
Practice Clean up the timer
Write a useEffect. Inside, call setInterval(tick, 1000) and assign the id to an id variable. The cleanup function should be () => clearInterval(id). Import useEffect from React.
Starter code
import React from 'react';
// Import useEffect from react
// Set up an interval and clean it up
export default function App() {
return null;
}Sample solution
import React, { useEffect } from 'react';
function tick() {}
export default function App() {
useEffect(() => {
const id = setInterval(tick, 1000);
return () => clearInterval(id);
}, []);
return null;
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the useEffect cleanup return
useEffect(() => {
const id = setInterval(tick, 1000);
____;
}, []);
useEffect(() => {
const id = setInterval(tick, 1000);
return () => clearInterval(id);
}, []);
Explanation: The cleanup clears the interval.
2 Match the memory leak causes
| Term | Meaning |
|---|---|
setInterval |
Uncleaned timer |
addListener |
Subscription leak |
setTimeout |
Pending timer |
WebSocket |
Open connection |
3 What should happen when a component unmounts?
- The useEffect cleanup function runs
- State is reset
- A new component is added Correct answer
- The app closes
Explanation: The cleanup function runs on unmount.