import React, { useState, useEffect } from 'react';
import { Text, View, ActivityIndicator } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
const PERSISTENCE_KEY = 'NAVIGATION_STATE_V1';
const Tab = createBottomTabNavigator();
function HomeScreen() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Welcome to the Home!</Text>
</View>
);
}
function ProfileScreen() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>This is your Profile</Text>
</View>
);
}
export default function App() {
const [isReady, setIsReady] = useState(false);
const [initialState, setInitialState] = useState();
useEffect(() => {
const restoreState = async () => {
try {
const savedStateString = await AsyncStorage.getItem(PERSISTENCE_KEY);
const state = savedStateString ? JSON.parse(savedStateString) : undefined;
if (state !== undefined) {
setInitialState(state);
}
} catch (e) {
// Ignore errors
} finally {
setIsReady(true);
}
};
restoreState();
}, []);
if (!isReady) {
return <ActivityIndicator size="large" style={{ flex: 1, justifyContent: 'center' }} />;
}
return (
<NavigationContainer
initialState={initialState}
onStateChange={(state) => AsyncStorage.setItem(PERSISTENCE_KEY, JSON.stringify(state))}
>
<Tab.Navigator>
<Tab.Screen name="Home" component={HomeScreen} />
<Tab.Screen name="Profile" component={ProfileScreen} />
</Tab.Navigator>
</NavigationContainer>
);
}
We use React Navigation's initialState prop to restore the last navigation state saved in AsyncStorage. When the app starts, useEffect runs once to load the saved state asynchronously. While loading, we show a spinner with ActivityIndicator.
Once loaded, we set initialState so the navigator opens the last visited tab. We also listen to navigation state changes with onStateChange and save the new state back to AsyncStorage. This way, the app remembers the last tab even after closing and reopening.
This approach improves user experience by keeping their place in the app.