Lesson 4 of 10
Memory Management - Avoiding Leaks
Memory leaks in React Native cause the app to slow down over time and eventually crash. The three main culprits are: uncleaned subscriptions in useEffect, event listeners not removed, and closures holding large objects.
Common Memory Leaks and Fixes
// ---- 1. Subscription cleanup ----
// ❌ LEAK: subscription never removed
useEffect(() => {
const sub = appStore.subscribe(update);
// missing return cleanup!
}, []);
// ✅ FIX:
useEffect(() => {
const sub = appStore.subscribe(update);
return () => sub.unsubscribe();
}, []);
// ---- 2. Event listeners ----
// ❌ LEAK
useEffect(() => {
AppState.addEventListener('change', handler);
}, []);
// ✅ FIX:
useEffect(() => {
const sub = AppState.addEventListener('change', handler);
return () => sub.remove();
}, []);
// ---- 3. Animated.Value + addListener ----
const anim = useRef(new Animated.Value(0)).current;
useEffect(() => {
const id = anim.addListener(({ value }) => console.log(value));
return () => anim.removeListener(id); // ← must remove!
}, []);
// ---- 4. Interval/timeout ----
useEffect(() => {
const id = setInterval(poll, 5000);
return () => clearInterval(id); // ← always clear
}, []);
// ---- 5. Image loading ----
// Large images decoded in memory can cause OOM on low-end Android
// Use expo-image - it pools decoded bitmaps
// Scale down large images before displaying:
import * as ImageManipulator from 'expo-image-manipulator';
async function compressImage(uri: string): Promise<string> {
const result = await ImageManipulator.manipulateAsync(
uri,
[{ resize: { width: 800 } }], // max 800px wide
{ compress: 0.8, format: ImageManipulator.SaveFormat.JPEG }
);
return result.uri;
}
// ---- 6. Large state objects ----
// Don't store full API responses in component state if list is long
// Keep only what's rendered - use TanStack Query's cache insteadTip
Tip
Practice Memory Management Avoiding Leaks in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Cleaning up timer closures, native event listeners, and heavy image bitmaps
Practice Task
Note
Practice Task - (1) Write a working example of Memory Management Avoiding Leaks from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Memory Management Avoiding Leaks is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react native code.
Finished this lesson?