App Lifecycle

Back

Loading concept...

App Lifecycle in React Native: Your App’s Life Story

The Universal Analogy: Your App is Like a Pet

Imagine your app is a pet dog living on someone’s phone. Sometimes the owner is playing with it (app is active). Sometimes they put it in another room while doing chores (app is in the background). And sometimes, the dog hears a loud noise and wants to run back to safety (the back button). The dog can also share toys with other pets (sharing content).

This is exactly how your React Native app behaves. Let’s meet the three magical helpers that manage this life cycle!


πŸ• AppState API: Knowing When Your App is Awake or Sleeping

What is AppState?

Think of AppState as a tiny spy inside your app. It constantly watches and tells you:

  • β€œHey! The user is looking at our app right now!” (active)
  • β€œUh oh, they switched to another app…” (background)
  • β€œThey’re coming back!” (active again)

Why Do We Need This?

Imagine you’re building a music app. When the user switches to Instagram:

  • Without AppState: Your music keeps playing loudly. Awkward!
  • With AppState: You can pause the music politely.

The Three States

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚     ACTIVE      β”‚  ← User is using your app
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚ User switches apps
         β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   BACKGROUND    β”‚  ← App is hidden but alive
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚ User returns
         β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚     ACTIVE      β”‚  ← Welcome back!
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

iOS has a bonus state: inactive - This happens briefly when:

  • A phone call comes in
  • The user pulls down the notification center

Simple Example

import { AppState } from 'react-native';

// Check current state right now
console.log(AppState.currentState);
// Prints: "active", "background", or "inactive"

// Listen for changes
AppState.addEventListener('change', (newState) => {
  if (newState === 'active') {
    console.log('User is back! Say hello!');
  } else if (newState === 'background') {
    console.log('User left. Save your work!');
  }
});

Real-World Uses

Scenario What You Do
Video playing Pause when backgrounded
Form with data Save draft when leaving
Live game Pause the timer
Chat app Stop polling for messages

Pro Tip: Clean Up!

useEffect(() => {
  const subscription = AppState.addEventListener(
    'change',
    handleAppStateChange
  );

  // Always remove listener when done!
  return () => {
    subscription.remove();
  };
}, []);

πŸ”™ BackHandler API: The Android Back Button Master

What is BackHandler?

On Android phones, there’s a back button (either physical or on-screen). When users press it, they expect something to happen. BackHandler lets YOU decide what!

iOS Note: iPhones don’t have a back button, so this API is Android-only. But your code won’t crash on iOS - it just does nothing.

The Big Question

When user presses back, what should happen?

  • Close a popup? βœ…
  • Go to previous screen? βœ…
  • Exit the app? βœ…
  • Do nothing? βœ…

You’re the boss!

How It Works

graph TD A["User Presses Back"] --> B{Your Handler} B -->|Return TRUE| C["You handled it - stop here"] B -->|Return FALSE| D["Let system handle it"] D --> E["Usually exits app or goes back"]

Simple Example

import { BackHandler } from 'react-native';

// When back is pressed...
BackHandler.addEventListener('hardwareBackPress', () => {
  // Return TRUE = "I handled it, don't do anything else"
  // Return FALSE = "I didn't handle it, do the default thing"

  if (isModalOpen) {
    closeModal();
    return true;  // We handled it!
  }

  return false;  // Let the system handle it
});

Common Patterns

Pattern 1: Close Modal First

const handleBackPress = () => {
  if (modalVisible) {
    setModalVisible(false);
    return true;
  }
  return false;
};

Pattern 2: Confirm Before Exit

const handleBackPress = () => {
  Alert.alert(
    'Wait!',
    'Are you sure you want to exit?',
    [
      { text: 'Stay', style: 'cancel' },
      { text: 'Exit', onPress: () => BackHandler.exitApp() }
    ]
  );
  return true;
};

Pattern 3: Navigate Back in Stack

const handleBackPress = () => {
  if (navigation.canGoBack()) {
    navigation.goBack();
    return true;
  }
  return false;
};

The React Hook Way

import { useFocusEffect } from '@react-navigation/native';

useFocusEffect(
  useCallback(() => {
    const onBackPress = () => {
      // Your logic here
      return true;
    };

    BackHandler.addEventListener(
      'hardwareBackPress',
      onBackPress
    );

    return () => BackHandler.removeEventListener(
      'hardwareBackPress',
      onBackPress
    );
  }, [])
);

Important Methods

Method What It Does
addEventListener() Start listening
removeEventListener() Stop listening
exitApp() Force close the app

🎁 Share API: Spreading Joy to Other Apps

What is Share?

The Share API opens that beautiful sheet you’ve seen a million times - the one that lets you send content to WhatsApp, Email, Twitter, or any other app!

It’s like telling your phone: β€œHey, I have something cool. Let the user choose where to send it!”

How Sharing Works

graph LR A["Your App"] -->|Share.share| B["System Share Sheet"] B --> C["WhatsApp"] B --> D["Email"] B --> E["Twitter"] B --> F["Messages"] B --> G["...Any App"]

Basic Example

import { Share } from 'react-native';

const shareMyStuff = async () => {
  try {
    const result = await Share.share({
      message: 'Check out this cool app!',
    });

    if (result.action === Share.sharedAction) {
      console.log('Shared successfully!');
    } else if (result.action === Share.dismissedAction) {
      console.log('User cancelled sharing');
    }
  } catch (error) {
    console.log('Oops:', error.message);
  }
};

What Can You Share?

Platform message url title
Android βœ… βœ… (in message) βœ… (shows in sheet)
iOS βœ… βœ… (separate) ❌ (ignored)

Complete Example

const shareContent = async () => {
  try {
    await Share.share(
      {
        message: 'I scored 100 points!',
        url: 'https://myapp.com/scores/123',
        title: 'My Amazing Score',
      },
      {
        dialogTitle: 'Share your score',  // Android only
        subject: 'Check my score!',       // Email subject
      }
    );
  } catch (error) {
    Alert.alert('Error', error.message);
  }
};

Share Results

After sharing, you get back a result:

{
  action: 'sharedAction' | 'dismissedAction',
  activityType: 'com.apple.UIKit.activity.Mail' // iOS only
}
  • sharedAction: User shared to some app
  • dismissedAction: User closed the sheet without sharing (iOS only)

Real World: Share Button Component

import { Share, TouchableOpacity, Text } from 'react-native';

const ShareButton = ({ message, url }) => {
  const onShare = async () => {
    try {
      await Share.share({ message, url });
    } catch (e) {
      console.log(e);
    }
  };

  return (
    <TouchableOpacity onPress={onShare}>
      <Text>Share</Text>
    </TouchableOpacity>
  );
};

// Usage
<ShareButton
  message="Look at this!"
  url="https://example.com"
/>

🎯 Putting It All Together

Here’s how these three APIs work as a team:

graph LR A["Your React Native App"] --> B["AppState API"] A --> C["BackHandler API"] A --> D["Share API"] B --> B1["Know when app is active/background"] B --> B2["Save data when leaving"] B --> B3["Refresh when returning"] C --> C1["Handle Android back button"] C --> C2["Close modals gracefully"] C --> C3["Confirm before exit"] D --> D1["Share text to any app"] D --> D2["Share URLs"] D --> D3["Let users spread the word"]

A Complete Screen Example

import React, { useEffect, useState } from 'react';
import {
  AppState,
  BackHandler,
  Share,
  View,
  Button,
  Text
} from 'react-native';

const MyScreen = () => {
  const [appState, setAppState] = useState(AppState.currentState);

  // 1. Track App State
  useEffect(() => {
    const sub = AppState.addEventListener('change', setAppState);
    return () => sub.remove();
  }, []);

  // 2. Handle Back Button
  useEffect(() => {
    const handler = () => {
      console.log('Back pressed!');
      return false; // Let system handle
    };
    BackHandler.addEventListener('hardwareBackPress', handler);
    return () => BackHandler.removeEventListener('hardwareBackPress', handler);
  }, []);

  // 3. Share Function
  const shareApp = () => {
    Share.share({ message: 'Try this app!' });
  };

  return (
    <View>
      <Text>App is: {appState}</Text>
      <Button title="Share" onPress={shareApp} />
    </View>
  );
};

🌟 Quick Summary

API Purpose Platform
AppState Know if app is active/background iOS + Android
BackHandler Control Android back button Android only
Share Open system share sheet iOS + Android

Remember

  1. AppState = Your app’s consciousness
  2. BackHandler = Your app’s reflexes (Android)
  3. Share = Your app’s social skills

Now your app knows when it’s awake, how to handle β€œgoing back,” and how to share its joy with the world!


Your app’s life cycle is now under your control. Go build something amazing!

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.