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
- AppState = Your appβs consciousness
- BackHandler = Your appβs reflexes (Android)
- 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!
