Bird
Raised Fist0
React Nativemobile~20 mins

Memory leak detection in React Native - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Memory Leak Detector
This screen helps detect and prevent memory leaks by showing a counter that updates every second. It includes a toggle button to start and stop the counter. Proper cleanup is implemented to avoid memory leaks.
Target UI
Memory Leak Detector

[Counter: 0]

[Start Counter]


Display a numeric counter starting at 0
Add a button labeled 'Start Counter' or 'Stop Counter' depending on state
When started, the counter increments by 1 every second
When stopped, the counter stops incrementing
Use useEffect hook with cleanup to prevent memory leaks
Toggle button text changes based on counter running state
Starter Code
React Native
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
  }
});
Task 1
Task 2
Task 3
Solution
React Native
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.

Final Result
Completed Screen
Memory Leak Detector

Counter: 0

[Start Counter]


When user taps 'Start Counter', the number increments by 1 every second
Button label changes to 'Stop Counter' while counting
When user taps 'Stop Counter', the counting stops
No memory leaks occur because timer is cleared properly
Stretch Goal
Add a reset button to set the counter back to zero
💡 Hint
Add another Button component with title 'Reset' that sets count state to 0 when pressed

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

  1. 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.
  2. Step 2: Identify the role of useEffect cleanup

    The cleanup function inside useEffect is used to clear timers or unsubscribe to prevent leaks.
  3. Final Answer:

    Not cleaning up subscriptions or timers in useEffect -> Option A
  4. 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?

useEffect(() => {
  const timer = setTimeout(() => console.log('Hi'), 1000);
  return () => ???
}, []);
easy
A. clearTimeout(timer);
B. clearInterval(timer);
C. cancelTimeout(timer);
D. stopTimer(timer);

Solution

  1. Step 1: Identify the timer type

    The timer is created with setTimeout, so it must be cleared with clearTimeout.
  2. Step 2: Match cleanup function

    The cleanup function should call clearTimeout(timer) to cancel the timer.
  3. Final Answer:

    clearTimeout(timer); -> Option A
  4. 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

  1. Step 1: Analyze useEffect without cleanup

    The interval is set but no cleanup function is returned, so it never stops.
  2. Step 2: Understand effect of missing cleanup

    When the component unmounts, the interval keeps running, causing a memory leak.
  3. Final Answer:

    The interval keeps running even after component unmount, causing memory leak -> Option D
  4. 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

  1. Step 1: Check subscription management

    The component subscribes to an API but does not unsubscribe on unmount.
  2. Step 2: Identify missing cleanup

    Without returning a cleanup function that calls subscription.unsubscribe(), the subscription stays active causing a leak.
  3. Final Answer:

    Missing cleanup function to unsubscribe from api -> Option B
  4. 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

  1. Step 1: Understand interval usage

    The component sets an interval to fetch data repeatedly every 5 seconds.
  2. Step 2: Prevent memory leak on unmount

    To stop the interval when the component unmounts, return a cleanup function that calls clearInterval(id).
  3. Final Answer:

    Return a cleanup function that calls clearInterval(id) -> Option C
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard