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

Handling Interruptions and Lifecycle Events

Manage app states effectively when hardware interrupts occur, such as incoming calls or app swaps.

In this lesson, you will learn how to make your app robust by responding gracefully when the operating system interrupts your app’s flow.

The Reality of Mobile Interruptions

Mobile apps don’t live in a vacuum. At any moment, a user might receive a phone call, swipe away to check a notification, or lock their screen. When this happens, your app shifts its "AppState." If your app is in the middle of a network request, a complex calculation, or playing a video, it needs to know whether to pause, save its progress, or stop entirely to conserve battery and system resources.

Listening to Lifecycle Events

React Native provides an AppState module to track these transitions. The three primary states you care about are:

  • active: The app is running in the foreground.
  • background: The app is running in the background (user swapped apps).
  • inactive: A transition state (e.g., the user is in the middle of a phone call or pulling down the notification shade).

By subscribing to changes in AppState, you can trigger specific logic. For example, you might want to pause a timer when the user leaves the app:

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

const App = () => {
  useEffect(() => {
    const subscription = AppState.addEventListener('change', (nextAppState) => {
      if (nextAppState === 'background') {
        console.log('App is now in the background. Saving user progress...');
      }
    });

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

  return <MyComponent />;
};

Why This Matters for Scaffolding

When you are scaffolding your project, handling these events prevents "zombie" processes. If you don't pause a background task—like an auto-refreshing data stream—the OS might eventually kill your app for consuming too much energy, or worse, your app might try to update the UI while it isn't visible, causing errors. By reacting to lifecycle events, you ensure your app is a "good citizen" of the operating system, providing a predictable experience for the user regardless of external hardware interrupts.

Key Takeaway: Always monitor your app's state to pause resource-intensive tasks when moving to the background and resume them gracefully when the user returns.