← Back to Chapters

React Native App State

? React Native App State

? Quick Overview

App State in React Native allows you to detect whether the application is in the foreground, background, or inactive state. It is commonly used to pause tasks, save data, refresh content, or handle app lifecycle events efficiently.

? Key Concepts

  • active – App is running in the foreground
  • background – App is running but not visible (e.g., user pressed home)
  • inactive – App is transitioning between states (common in iOS)

? Syntax / Theory

React Native provides the AppState API to subscribe to app lifecycle changes. You can listen to state changes using event listeners and respond accordingly.

? View Code Example
// Import AppState from react-native
import { AppState } from "react-native";

// Get the current app state
const currentState = AppState.currentState;

? Code Example

? View Code Example
// Track app state changes using useEffect
import React, { useEffect, useState } from "react";
import { View, Text, AppState } from "react-native";

export default function App() {
  const [appState, setAppState] = useState(AppState.currentState);

  useEffect(() => {
    // Listener for state changes
    const subscription = AppState.addEventListener("change", nextState => {
      console.log("App State changed to:", nextState);
      setAppState(nextState);
    });

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

  return (
    <View>
      <Text>Current App State: {appState}</Text>
    </View>
  );
}

? Live Output / Explanation

Explanation

When the app moves between foreground and background, the AppState listener updates the state variable. The UI automatically reflects the current app state.

? Interactive Example

Since we are in a browser, we can simulate App State behavior using browser tabs. When you switch tabs or minimize the window, the state changes to "background". When you return, it becomes "active".

active
-- Ready to track state --

? Action: Switch to a new browser tab and come back here to see the log update!

? Use Cases

  • Pause video or audio when app goes to background
  • Save form data automatically
  • Refresh API data when app becomes active
  • Detect inactivity for security purposes (e.g., banking apps)

? Tips & Best Practices

  • Always remove AppState listeners to avoid memory leaks.
  • Use AppState sparingly for performance-sensitive logic.
  • Combine with timers for specific inactivity detection.

? Try It Yourself

  1. Log app state changes in the console.
  2. Show an alert when app goes to background.
  3. Store last active time using AsyncStorage.