This React Native component demonstrates how to detect and prevent memory leaks by properly cleaning up asynchronous tasks and subscriptions when the component unmounts.
Widget Tree
App
└── View
├── Text (Status)
└── Button (Start Task)
The root component <App> renders a <View> container. Inside the View, there is a <Text> component showing the current status message, and a <Button> that starts a simulated asynchronous task.
Render Trace - 6 Steps
Step 1: App
Step 2: Button
Step 3: App (after button press)
Step 4: Async Task (simulated with setTimeout)
Step 5: App (component unmount)
Step 6: Async Task completion
State Change - Re-render
Trigger:User presses 'Start Task' button
Before
{status: 'Idle', taskRunning: false}
→
After
{status: 'Task running...', taskRunning: true}
Re-renders:Entire App component re-renders to update status text
UI Quiz - 3 Questions
Test your understanding
What happens if the component unmounts before the async task finishes?
AThe cleanup cancels the task to prevent memory leaks.
BThe task continues and updates state causing an error.
CNothing happens; the task completes normally.
DThe app crashes immediately.
Key Insight
In React Native, asynchronous tasks like timers or subscriptions can cause memory leaks if not cleaned up properly. Always use cleanup functions in useEffect or componentWillUnmount to cancel these tasks. This prevents errors and keeps your app smooth and stable.
Practice
(1/5)
1.
What is a common cause of memory leaks in React Native apps?
useEffect hooks that do not clean up resources properly.
easy
A. Not cleaning up subscriptions or timers in useEffect
B. Using too many View components
C. Writing styles inline instead of in StyleSheet
D. Using functional components instead of class components
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 useEffect cleanup
The cleanup function inside useEffect is used to clear timers or unsubscribe to prevent leaks.
Final Answer:
Not cleaning up subscriptions or timers in useEffect -> Option A
Quick Check:
Failing to cleanup in useEffect causes leaks = B [OK]
Hint: Always clean timers and subscriptions in useEffect cleanup [OK]
Common Mistakes:
Ignoring cleanup functions in useEffect
Confusing styling issues with memory leaks
Thinking functional components cause leaks
2.
Which of the following is the correct syntax to clean up a timer inside useEffect?
The timer is created with setTimeout, so it must be cleared with clearTimeout.
Step 2: Match cleanup function
The cleanup function should call clearTimeout(timer) to cancel the timer.
Final Answer:
clearTimeout(timer); -> Option A
Quick Check:
setTimeout cleared by clearTimeout = A [OK]
Hint: Match setTimeout with clearTimeout in cleanup [OK]
Common Mistakes:
Using clearInterval for setTimeout
Using non-existent cancelTimeout or stopTimer
Forgetting to return cleanup function
3.
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;
}
medium
A. The component will throw a syntax error
B. The interval stops automatically when component unmounts
C. The interval runs only once and stops
D. The interval keeps running even after component unmount, causing memory leak
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 D
Quick Check:
No cleanup means interval runs forever = C [OK]
Hint: No cleanup in useEffect means timers leak [OK]
Common Mistakes:
Assuming intervals stop automatically
Confusing syntax errors with runtime leaks
Thinking interval runs only once
4.
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;
}
medium
A. Empty dependency array in useEffect
B. Missing cleanup function to unsubscribe from api
C. Not returning JSX from component
D. Using arrow function inside useEffect
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 calls subscription.unsubscribe(), the subscription stays active causing a leak.
Final Answer:
Missing cleanup function to unsubscribe from api -> Option B
Quick Check:
Missing subscription cleanup causes leak = D [OK]
Hint: Always unsubscribe in useEffect cleanup [OK]
Common Mistakes:
Thinking arrow functions cause leaks
Confusing JSX return with memory leaks
Ignoring cleanup for subscriptions
5.
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;
}
hard
A. Remove the dependency array from useEffect
B. Call fetchData() once outside useEffect
C. Return a cleanup function that calls clearInterval(id)
D. Use setTimeout instead of setInterval without cleanup
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 calls clearInterval(id).
Final Answer:
Return a cleanup function that calls clearInterval(id) -> Option C
Quick Check:
Clear intervals in cleanup to avoid leaks = A [OK]
Hint: Always clear intervals in useEffect cleanup [OK]
Common Mistakes:
Removing dependency array breaks effect logic
Using setTimeout without cleanup causes leaks
Calling fetchData only once misses polling
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.