Memory Leak Detector [Counter: 0] [Start Counter]
Memory leak detection in React Native - Mini App: Build & Ship
import React, { useState, useEffect } from 'react'; import { View, Text, Button, StyleSheet } from 'react-native'; export default function MemoryLeakDetector() { const [count, setCount] = useState(0); const [running, setRunning] = useState(false); // TODO: Add useEffect to handle counter increment and cleanup return ( <View style={styles.container}> <Text style={styles.counter}>Counter: {count}</Text> <Button title={running ? 'Stop Counter' : 'Start Counter'} onPress={() => setRunning(!running)} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 16 }, counter: { fontSize: 32, marginBottom: 20 } });
import React, { useState, useEffect } from 'react'; import { View, Text, Button, StyleSheet } from 'react-native'; export default function MemoryLeakDetector() { const [count, setCount] = useState(0); const [running, setRunning] = useState(false); useEffect(() => { if (!running) return; const intervalId = setInterval(() => { setCount(c => c + 1); }, 1000); return () => clearInterval(intervalId); }, [running]); return ( <View style={styles.container}> <Text style={styles.counter}>Counter: {count}</Text> <Button title={running ? 'Stop Counter' : 'Start Counter'} onPress={() => setRunning(!running)} accessibilityLabel={running ? 'Stop the counter' : 'Start the counter'} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 16 }, counter: { fontSize: 32, marginBottom: 20 } });
This solution uses the useEffect hook to start a timer only when the counter is running. The timer increments the count state every second. When the running state changes or the component unmounts, the cleanup function clears the timer to prevent memory leaks. The button toggles the running state and updates its label accordingly. Accessibility label is added for better screen reader support.
Memory Leak Detector Counter: 0 [Start Counter]
Practice
What is a common cause of memory leaks in React Native apps?
useEffect hooks that do not clean up resources properly.
Solution
Step 1: Understand memory leaks in React Native
Memory leaks often happen when resources like timers or subscriptions are not cleaned up after a component unmounts.Step 2: Identify the role of
The cleanup function insideuseEffectcleanupuseEffectis used to clear timers or unsubscribe to prevent leaks.Final Answer:
Not cleaning up subscriptions or timers inuseEffect-> Option AQuick Check:
Failing to cleanup in useEffect causes leaks = B [OK]
- Ignoring cleanup functions in useEffect
- Confusing styling issues with memory leaks
- Thinking functional components cause leaks
Which of the following is the correct syntax to clean up a timer inside useEffect?
useEffect(() => {
const timer = setTimeout(() => console.log('Hi'), 1000);
return () => ???
}, []);Solution
Step 1: Identify the timer type
The timer is created withsetTimeout, so it must be cleared withclearTimeout.Step 2: Match cleanup function
The cleanup function should callclearTimeout(timer)to cancel the timer.Final Answer:
clearTimeout(timer); -> Option AQuick Check:
setTimeout cleared by clearTimeout = A [OK]
- Using clearInterval for setTimeout
- Using non-existent cancelTimeout or stopTimer
- Forgetting to return cleanup function
What will happen if the following React Native component does NOT clean up the interval?
function Timer() {
React.useEffect(() => {
const id = setInterval(() => console.log('tick'), 1000);
}, []);
return null;
}Solution
Step 1: Analyze useEffect without cleanup
The interval is set but no cleanup function is returned, so it never stops.Step 2: Understand effect of missing cleanup
When the component unmounts, the interval keeps running, causing a memory leak.Final Answer:
The interval keeps running even after component unmount, causing memory leak -> Option DQuick Check:
No cleanup means interval runs forever = C [OK]
- Assuming intervals stop automatically
- Confusing syntax errors with runtime leaks
- Thinking interval runs only once
Identify the bug causing a memory leak in this React Native component:
function DataFetcher() {
React.useEffect(() => {
const subscription = api.subscribe(data => console.log(data));
// Missing cleanup function here
}, []);
return null;
}Solution
Step 1: Check subscription management
The component subscribes to an API but does not unsubscribe on unmount.Step 2: Identify missing cleanup
Without returning a cleanup function that callssubscription.unsubscribe(), the subscription stays active causing a leak.Final Answer:
Missing cleanup function to unsubscribe from api -> Option BQuick Check:
Missing subscription cleanup causes leak = D [OK]
- Thinking arrow functions cause leaks
- Confusing JSX return with memory leaks
- Ignoring cleanup for subscriptions
You have a React Native component that fetches data every 5 seconds using setInterval. How should you modify the code to prevent memory leaks when the component unmounts?
function PollingComponent() {
React.useEffect(() => {
const id = setInterval(() => fetchData(), 5000);
// What goes here?
}, []);
return null;
}Solution
Step 1: Understand interval usage
The component sets an interval to fetch data repeatedly every 5 seconds.Step 2: Prevent memory leak on unmount
To stop the interval when the component unmounts, return a cleanup function that callsclearInterval(id).Final Answer:
Return a cleanup function that calls clearInterval(id) -> Option CQuick Check:
Clear intervals in cleanup to avoid leaks = A [OK]
- Removing dependency array breaks effect logic
- Using setTimeout without cleanup causes leaks
- Calling fetchData only once misses polling
Ready to prove it?
Pass the test and this pattern moves unknown
