A mobile app spends a lot of its life out of sight: the user switches apps, locks the phone or pulls down a system panel, then comes back minutes or hours later. Data loaded before the switch can be stale by then, and a timer may need to pause while nobody is looking. React Native's AppState module tells you whether the app is in the foreground or the background, and calls you back each time that changes.
Key terms
AppState: the module that reports whether the app is in the foreground or the background and notifies listeners when that changes.AppState.currentState: the app's current state, which React Native keeps up to date.change: the AppState event whose listener receives the new state each time it changes.blurandfocus: Android-only AppState events for when the user stops or starts interacting with the app.
The values AppState reports
Most code deals with three values:
active: the app is running in the foreground.background: the app is running in the background. The user is in another app or on the home screen, or, on Android, another Activity is on top. That includes temporary system activities such as autofill credential pickers, even when your own app launched them.inactive: iOS only. It shows up during the transition between foreground and background, and during interruptions such as the multitasking view, the Notification Center or an incoming call.
Android's native module only defines active and background, so an Android app never reports inactive. The state becomes active when the host activity resumes and background when it pauses. So the autofill case is a real one on Android: a credential picker sends your Android app to background and back to active, although the user never left.
The AppStateStatus type lists two more values, extension and unknown. On iOS, the native module reports extension inside an app extension, and unknown when the UIKit application state matches none of the three main values. A switch over the state should give them a default branch.
Reading the state and subscribing
AppState.currentState holds the current state. Its type is null | undefined | string, because it can be null until the initial value is set. With the legacy architecture it is null at launch, until the value arrives asynchronously from native code. AppState keeps the field fresh with a listener of its own, whether or not your code subscribes.
To react to changes, call AppState.addEventListener('change', listener). The listener receives the new state, and the call returns an EventSubscription whose remove() method unsubscribes it, so call that in your effect's cleanup. Four event names are accepted: change, memoryWarning, blur and focus. Any other name throws Trying to subscribe to unknown event. memoryWarning is iOS only and fires when the operating system sends the app a memory warning.
On iOS, a change event is only sent when the new state differs from the last one, so your listener never sees the same value twice in a row. Coming back from the home screen produces a single change to active: iOS reports the "will enter foreground" step as background, which matches the state the app is already in, so no event goes out for it.
Spotting a return to the foreground
The listener only receives the new state. To know the app came back, compare it with the previous one, which you keep in a ref initialized with AppState.currentState. The useOnForeground hook below uses this check:
tsxlastState.current?.match(/inactive|background/) && nextState === 'active'
The optional chaining is there because the ref may start out null. After the check, the listener stores every new state with lastState.current = nextState, matched or not, so each change is compared with the one right before it.
Because the pattern matches inactive too, the branch also runs after short iOS interruptions. Open the Notification Center and close it, and the listener sees inactive and then active, so the check fires although the app never reached the background. If only real trips to the background should count, match background alone.
Refreshing an inbox on return
The InboxScreen example below loads messages with fetch when it mounts, and loads them again every time the app returns to the foreground. The useOnForeground hook holds the AppState logic: it subscribes in an effect, runs the comparison above and removes the subscription in the cleanup.
loadMessages checks response.ok and catches its own errors, like OrdersScreen. Its useCallback has no dependencies, so the hook's effect sees the same function on every render and subscribes once. If a screen renders the current state, it will only ever show active, because the app is only visible to the user while it is active.
Android's focus and blur
Pulling down the notification drawer on Android does not change the app state. The app stays active, and AppState fires blur instead. focus fires when the app gains focus again and the user is back to interacting with it.
Both events listen to a single native event, appStateFocusChange, which the iOS module never emits and does not support. Subscribing on iOS is not harmless: a debug build shows `appStateFocusChange` is not a supported event type for RCTAppState on a red error screen. Register them on Android only, as in this quiz timer that pauses while the drawer is open:
tsxuseEffect(() => { if (Platform.OS !== 'android') { return; } const blur = AppState.addEventListener('blur', () => setPaused(true)); const focus = AppState.addEventListener('focus', () => setPaused(false)); return () => { blur.remove(); focus.remove(); }; }, []);
On iOS, the comparable interruption, opening the Notification Center, shows up as inactive in the change event instead.
Code Examples
import {useCallback, useEffect, useRef, useState} from 'react';
import {AppState, FlatList, Text, View} from 'react-native';
type Message = {id: string; subject: string};
function useOnForeground(onForeground: () => void) {
const lastState = useRef(AppState.currentState);
useEffect(() => {
const subscription = AppState.addEventListener('change', nextState => {
if (
lastState.current?.match(/inactive|background/) &&
nextState === 'active'
) {
onForeground();
}
lastState.current = nextState;
});
return () => subscription.remove();
}, [onForeground]);
}
export function InboxScreen() {
const [messages, setMessages] = useState<Message[]>([]);
const [error, setError] = useState<string | null>(null);
const loadMessages = useCallback(async () => {
try {
const response = await fetch('https://api.example.com/messages');
if (!response.ok) {
throw new Error(`Server returned ${response.status}`);
}
setMessages((await response.json()) as Message[]);
setError(null);
} catch (e) {
setError(e instanceof Error ? e.message : 'Request failed');
}
}, []);
useEffect(() => {
loadMessages();
}, [loadMessages]);
useOnForeground(loadMessages);
return (
<View>
{error && <Text>Could not refresh: {error}</Text>}
<FlatList
data={messages}
keyExtractor={message => message.id}
renderItem={({item}) => <Text>{item.subject}</Text>}
/>
</View>
);
}