Skip to main content

Overview

The useHistory hook provides access to the global navigation history store. Use this hook to query recent screens, track navigation paths, or build features that depend on navigation history across your entire app.

Import

import { useHistory } from 'react-native-screen-transitions';

Usage

import { useHistory } from 'react-native-screen-transitions';

function MyComponent() {
  const { getRecent, getPath, history } = useHistory();

  // Get last 5 visited screens
  const recentScreens = getRecent(5);
  
  // Get path between two screens
  const path = getPath('screen-key-1', 'screen-key-2');
  
  // Access full history
  console.log('Total screens in history:', history.size);

  return <View />;
}

Return Value

Returns a UseHistoryReturn object with the following properties:
history
ReadonlyMap<ScreenKey, HistoryEntry>
The full history map. Keys are screen keys, values are history entries containing timestamp, route info, and navigator context.
getRecent
(n: number) => HistoryEntry[]
Get N most recent history entries, ordered with most recent first.Parameters:
  • n (number): Number of entries to retrieve
Returns: Array of HistoryEntry objects
getByNavigator
(navigatorKey: string) => HistoryEntry[]
Get history entries for a specific navigator, ordered with most recent first.Parameters:
  • navigatorKey (string): The key of the navigator
Returns: Array of HistoryEntry objects from that navigator
getPath
(fromKey: ScreenKey, toKey: ScreenKey) => ScreenKey[]
Get the navigation path between two screens for multi-waypoint interpolation.Parameters:
  • fromKey (ScreenKey): Starting screen key
  • toKey (ScreenKey): Ending screen key
Returns: Array of screen keys in order from fromKey to toKey
get
(screenKey: ScreenKey) => HistoryEntry | undefined
Get a specific history entry by screen key.Parameters:
  • screenKey (ScreenKey): The unique key for the screen
Returns: HistoryEntry if found, undefined otherwise
getMostRecent
() => HistoryEntry | undefined
Get the most recent history entry (useful for forward navigation).Returns: Most recent HistoryEntry or undefined if history is empty

HistoryEntry Type

Each history entry contains:
  • screenKey (ScreenKey): Unique key for the screen
  • routeName (string): Name of the route
  • navigatorKey (string): Key of the navigator containing this screen
  • timestamp (number): When this entry was created
  • params (object): Route parameters

Examples

Display Recent Screens

import { useHistory } from 'react-native-screen-transitions';

function RecentScreensList() {
  const { getRecent } = useHistory();
  const recentScreens = getRecent(5);

  return (
    <View>
      <Text>Recently Visited:</Text>
      {recentScreens.map((entry) => (
        <Text key={entry.screenKey}>
          {entry.routeName} - {new Date(entry.timestamp).toLocaleTimeString()}
        </Text>
      ))}
    </View>
  );
}

Track Navigation Path

import { useHistory } from 'react-native-screen-transitions';

function NavigationPathViewer({ fromKey, toKey }) {
  const { getPath } = useHistory();
  const path = getPath(fromKey, toKey);

  return (
    <View>
      <Text>Navigation Path:</Text>
      {path.map((screenKey, index) => (
        <Text key={screenKey}>
          {index + 1}. {screenKey}
        </Text>
      ))}
    </View>
  );
}

Filter by Navigator

import { useHistory } from 'react-native-screen-transitions';

function NavigatorHistory({ navigatorKey }) {
  const { getByNavigator } = useHistory();
  const entries = getByNavigator(navigatorKey);

  return (
    <View>
      <Text>History for {navigatorKey}:</Text>
      <Text>Total screens: {entries.length}</Text>
      {entries.map((entry) => (
        <View key={entry.screenKey}>
          <Text>{entry.routeName}</Text>
          <Text>Params: {JSON.stringify(entry.params)}</Text>
        </View>
      ))}
    </View>
  );
}

Check if User Visited a Screen

import { useHistory } from 'react-native-screen-transitions';

function OnboardingCheck() {
  const { history } = useHistory();
  
  const hasSeenOnboarding = Array.from(history.values()).some(
    (entry) => entry.routeName === 'Onboarding'
  );

  if (!hasSeenOnboarding) {
    return <OnboardingScreen />;
  }

  return <HomeScreen />;
}

Build Breadcrumbs

import { useHistory } from 'react-native-screen-transitions';
import { useNavigation } from '@react-navigation/native';

function Breadcrumbs() {
  const { getRecent } = useHistory();
  const navigation = useNavigation();
  const recentScreens = getRecent(3).reverse(); // Oldest first

  return (
    <View style={{ flexDirection: 'row' }}>
      {recentScreens.map((entry, index) => (
        <View key={entry.screenKey} style={{ flexDirection: 'row' }}>
          <Pressable onPress={() => navigation.navigate(entry.routeName, entry.params)}>
            <Text>{entry.routeName}</Text>
          </Pressable>
          {index < recentScreens.length - 1 && <Text> > </Text>}
        </View>
      ))}
    </View>
  );
}

Analytics Tracking

import { useHistory } from 'react-native-screen-transitions';
import { useEffect } from 'react';

function AnalyticsTracker() {
  const { getMostRecent } = useHistory();

  useEffect(() => {
    const mostRecent = getMostRecent();
    
    if (mostRecent) {
      // Track screen view
      analytics.track('screen_view', {
        screen_name: mostRecent.routeName,
        screen_key: mostRecent.screenKey,
        navigator: mostRecent.navigatorKey,
        params: mostRecent.params,
        timestamp: mostRecent.timestamp,
      });
    }
  }, [getMostRecent]);

  return null;
}

Prevent Back Navigation to Specific Screens

import { useHistory } from 'react-native-screen-transitions';
import { useNavigation } from '@react-navigation/native';
import { useEffect } from 'react';

function ProtectedScreen() {
  const { getRecent } = useHistory();
  const navigation = useNavigation();

  useEffect(() => {
    const recent = getRecent(2);
    const previousScreen = recent[1]; // Second most recent

    if (previousScreen?.routeName === 'Login') {
      // Prevent going back to login after authentication
      navigation.reset({
        index: 0,
        routes: [{ name: 'Home' }],
      });
    }
  }, [getRecent, navigation]);

  return <View />;
}

Notes

The history store subscribes to navigation changes globally, so useHistory can be called from any component, not just screen components.
History entries persist throughout the app’s lifecycle but are cleared when the app is closed. Consider using AsyncStorage or another persistence mechanism if you need to preserve history across app sessions.
The getPath function is particularly useful for multi-waypoint animations where you need to animate through intermediate screens.