0
0
React Nativemobile~5 mins

Navigation state persistence in React Native

Choose your learning style9 modes available
Introduction

Navigation state persistence helps your app remember where you were last time you used it. This way, when you open the app again, it shows the same screen instead of starting over.

When you want users to continue where they left off after closing the app.
When your app has multiple screens and users switch between them often.
When you want to improve user experience by saving navigation history.
When your app needs to restore state after being killed by the system.
When you want to save deep links or special screen states for users.
Syntax
React Native
import React from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { NavigationContainer } from '@react-navigation/native';

const PERSISTENCE_KEY = 'NAVIGATION_STATE';

export default function App() {
  const [isReady, setIsReady] = React.useState(false);
  const [initialState, setInitialState] = React.useState();

  React.useEffect(() => {
    const restoreState = async () => {
      try {
        const savedStateString = await AsyncStorage.getItem(PERSISTENCE_KEY);
        const state = savedStateString ? JSON.parse(savedStateString) : undefined;
        if (state) {
          setInitialState(state);
        }
      } finally {
        setIsReady(true);
      }
    };

    if (!isReady) {
      restoreState();
    }
  }, [isReady]);

  if (!isReady) {
    return null; // or a loading indicator
  }

  return (
    <NavigationContainer
      initialState={initialState}
      onStateChange={(state) =>
        AsyncStorage.setItem(PERSISTENCE_KEY, JSON.stringify(state))
      }
    >
      {/* Your navigators here */}
    </NavigationContainer>
  );
}

Use AsyncStorage to save and load navigation state asynchronously.

Wrap your app in NavigationContainer and provide initialState and onStateChange props.

Examples
This saves the navigation state as a string in storage.
React Native
const PERSISTENCE_KEY = 'NAV_STATE';

// Save state
AsyncStorage.setItem(PERSISTENCE_KEY, JSON.stringify(state));
This loads the saved state and parses it back to an object.
React Native
const savedStateString = await AsyncStorage.getItem(PERSISTENCE_KEY);
const state = savedStateString ? JSON.parse(savedStateString) : undefined;
This sets up the navigation container to restore and save state automatically.
React Native
<NavigationContainer
  initialState={initialState}
  onStateChange={state => AsyncStorage.setItem(PERSISTENCE_KEY, JSON.stringify(state))}
>
Sample App

This app has two screens: Home and Details. When you navigate between them, the app saves your place. If you close and reopen the app, it opens the screen you last visited.

React Native
import React from 'react';
import { View, Text, Button } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

const Stack = createStackNavigator();
const PERSISTENCE_KEY = 'NAVIGATION_STATE';

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button title="Go to Details" onPress={() => navigation.navigate('Details')} />
    </View>
  );
}

function DetailsScreen() {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Details Screen</Text>
    </View>
  );
}

export default function App() {
  const [isReady, setIsReady] = React.useState(false);
  const [initialState, setInitialState] = React.useState();

  React.useEffect(() => {
    const restoreState = async () => {
      try {
        const savedStateString = await AsyncStorage.getItem(PERSISTENCE_KEY);
        const state = savedStateString ? JSON.parse(savedStateString) : undefined;
        if (state) {
          setInitialState(state);
        }
      } finally {
        setIsReady(true);
      }
    };

    if (!isReady) {
      restoreState();
    }
  }, [isReady]);

  if (!isReady) {
    return null;
  }

  return (
    <NavigationContainer
      initialState={initialState}
      onStateChange={(state) => AsyncStorage.setItem(PERSISTENCE_KEY, JSON.stringify(state))}
    >
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Details" component={DetailsScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}
OutputSuccess
Important Notes

Make sure to install @react-native-async-storage/async-storage to use AsyncStorage.

Saving state on every navigation change may affect performance on very large apps; consider throttling if needed.

Test on both Android and iOS devices as storage behavior can differ slightly.

Summary

Navigation state persistence saves where the user is in the app.

Use AsyncStorage to save and restore navigation state.

Wrap your app in NavigationContainer with initialState and onStateChange props.