Course contentsShow
← React Native
Lesson 109 of 1,5552. Project Scaffolding with ExpoFree lesson

Native Module Lifecycle Management

Initialize and clean up native resources appropriately during app foregrounding and backgrounding.

In this lesson, you will learn how to synchronize your app’s native resources with the user’s activity to ensure your app stays performant and battery-friendly.

When you build or use native modules in an Expo project, they often act as bridges to hardware resources—like a camera stream, a socket connection, or a sensor. These resources are "expensive" in terms of memory and battery. If you leave a camera stream running while the user minimizes your app to check a text message, your app will continue to drain the phone's battery, and the system might even kill your app for mismanaging resources.

Managing the Lifecycle

Native module lifecycle management is the practice of "hooking" into the app's state changes to initialize or release these native resources. In Expo, we typically use the AppState API from react-native to detect when the app moves between the foreground (active) and background (hidden).

Consider a native module that tracks GPS coordinates. You don't want that module working when the user isn't looking at your app. You would manage it like this:

import { useEffect } from 'react';
import { AppState } from 'react-native';

const useLocationTracker = () => {
  useEffect(() => {
    const subscription = AppState.addEventListener('change', (nextAppState) => {
      if (nextAppState === 'active') {
        // App is now visible: Start the native module resource
        NativeModule.startTracking();
      } else {
        // App is in background: Clean up the native resource
        NativeModule.stopTracking();
      }
    });

    return () => subscription.remove();
  }, []);
};

By observing the AppState transitions, you ensure that the heavy lifting—the "native-side" work—is only active when the user is interacting with your interface.

Why this matters

Failing to clean up these resources leads to "memory leaks." If you repeatedly open and close your app without releasing native objects, the memory usage will climb until the operating system forces a crash to reclaim space. By explicitly starting and stopping these services during lifecycle transitions, you make your app a "good citizen" of the mobile operating system.

Key Takeaway: Always release native hardware resources when your app moves to the background to save battery and prevent memory-related crashes.