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.
React Native provides the AppState API to subscribe to app lifecycle changes. You can listen to state changes using event listeners and respond accordingly.
// Import AppState from react-native
import { AppState } from "react-native";
// Get the current app state
const currentState = AppState.currentState;
// 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>
);
}
When the app moves between foreground and background, the AppState listener updates the state variable. The UI automatically reflects the current app state.
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".
? Action: Switch to a new browser tab and come back here to see the log update!
AppState listeners to avoid memory leaks.AsyncStorage.