Memory leaks happen when your app keeps using memory it no longer needs. Detecting them helps your app run smoothly and not slow down or crash.
Memory leak detection in React Native
useEffect(() => {
// setup code
return () => {
// cleanup code to avoid memory leaks
};
}, [dependencies]);Always clean up timers, subscriptions, or event listeners inside the return function of useEffect.
This cleanup runs when the component unmounts or before the effect runs again.
useEffect(() => {
const timer = setTimeout(() => {
console.log('Hello');
}, 1000);
return () => clearTimeout(timer);
}, []);useEffect(() => {
const subscription = someEventEmitter.addListener('event', () => {
console.log('Event happened');
});
return () => subscription.remove();
}, []);This React Native component shows a count that increases every second. It uses setInterval inside useEffect and clears it when the component unmounts to avoid memory leaks.
import React, { useState, useEffect } from 'react'; import { View, Text, Button } from 'react-native'; export default function TimerExample() { const [count, setCount] = useState(0); useEffect(() => { const interval = setInterval(() => { setCount(c => c + 1); }, 1000); return () => clearInterval(interval); // cleanup to prevent memory leak }, []); return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>Count: {count}</Text> <Button title="Reset" onPress={() => setCount(0)} /> </View> ); }
Memory leaks can cause your app to slow down or crash over time.
Always clean up side effects like timers, subscriptions, or event listeners in useEffect.
Use React Native debugging tools or profiling tools to monitor memory usage.
Memory leaks happen when resources are not released properly.
Use the cleanup function in useEffect to prevent leaks.
Detect leaks by watching app performance and memory use over time.