Course contentsShow
← React Native
Lesson 216 of 1,5553. Core Primitive ComponentsFree lesson

Managing Component Unmount Lifecycle

Learners will clean up listeners and timers to prevent memory leaks in the view tree.

In this lesson, you will learn how to prevent memory leaks by cleaning up background processes when a component is removed from your app’s view tree.

Why Components Leave the Party

In React Native, components are constantly being mounted (added to the screen) and unmounted (removed from the screen). For example, when a user navigates away from a screen or closes a modal, that screen component "unmounts."

If your component started a timer or began listening for a device event, those tasks don't stop automatically just because the UI disappeared. They continue running in the background, consuming memory and processing power. This is called a memory leak, and if you ignore it, your app will eventually slow down or crash.

The Cleanup Strategy

To prevent this, we use the cleanup function inside the useEffect hook. Think of this as a "goodbye" phase. When React prepares to remove your component, it runs the function you return from useEffect.

Here is how you handle a timer that might otherwise keep running forever:

import React, { useEffect } from 'react';

const TimerComponent = () => {
  useEffect(() => {
    // Start a timer when the component mounts
    const interval = setInterval(() => {
      console.log('Doing background work...');
    }, 1000);

    // This return function runs exactly when the component unmounts
    return () => {
      clearInterval(interval);
      console.log('Timer cleared, memory saved!');
    };
  }, []);

  return <Text>Watch the console for the timer.</Text>;
};

How it works

  1. The Setup: The setInterval starts ticking as soon as the component appears.
  2. The Cleanup: By returning a function inside useEffect, you tell React: "Before you destroy this component, run this piece of code first."
  3. The Result: clearInterval(interval) kills the timer process, ensuring it doesn't try to update a component that no longer exists.

You should apply this same logic whenever you subscribe to external listeners (like keyboard events or device orientation changes). Always "turn off the lights" when you leave the room.

Key Takeaway: Always return a cleanup function in your useEffect to stop timers and listeners, ensuring your app stays performant and leak-free when components are removed.