JavaScript and React course ยท Module 6: React Router

Managing Browser History on a Journey Through Cosmic Time

12 min read ยท
In this lesson12

In intergalactic travels, it's important to track the route and have the ability to return to previous exploration points. In the world of React Router, this navigation system is the browser history - a mechanism that allows moving back and forth between visited pages. Let's see how to consciously manage history to increase the comfort of users' journeys through our application.

Browser History Basics

Browser history is a stack of URL addresses visited by the user. Browsers provide an API that allows:

  • Moving back and forth between pages
  • Adding new entries to the history
  • Replacing the current entry
  • Manipulating the history state

React Router integrates with this API, providing hooks and components for managing history in a React-friendly way.

The useNavigate Hook

The useNavigate hook is the primary tool for programmatic navigation in React Router:

import { useNavigate } from 'react-router-dom';

function MissionControl() {
  const navigate = useNavigate();

  const goToExploration = () => {
    navigate('/exploration');
  };

  const goBack = () => {
    navigate(-1); // Go back one page
  };

  const goForward = () => {
    navigate(1);  // Go forward one page
  };

  const jumpToSpecificPoint = () => {
    navigate(-3); // Go back three pages
  };

  return (
    <div className="mission-control">
      <h1>Mission Control Center</h1>

      <div className="navigation-panel">
        <button onClick={goToExploration}>Start Exploration</button>
        <button onClick={goBack}>Return to previous location</button>
        <button onClick={goForward}>Forward</button>
        <button onClick={jumpToSpecificPoint}>Return to starting point</button>
      </div>
    </div>
  );
}

Replacing vs. Adding to History

When using navigate, we can decide whether to add a new page to history or replace the current one:

// Add a new page to the history stack (default behavior)
navigate('/new-location');

// Replace the current page in history
navigate('/new-location', { replace: true });

When should you use replace: true?

  1. Redirects after login/logout - we don't want the user to be able to return to the login page after logging in
  2. Multi-step forms - we don't want the user to be able to return to intermediate steps of the process
  3. Redirects from non-existent pages - when redirecting from 404 to the home page
  4. When performing a redirect - to avoid loops in browser history

Blocking Navigation

Sometimes we need to prevent the user from leaving a page, for example when they have unsaved changes in a form. Imagine the spaceship configurator: an astronaut has typed in the ship's name and picked the engines but has not saved the configuration yet, and accidentally clicks a link to the hangar or the "Back" button. Without a warning, all that work is lost.

React Router has a built-in hook for this: useBlocker. It appeared in version 6.7 as unstable_useBlocker, has been stable since version 6.19 and also works in v7 and v8. You already know the condition from the lesson on nested routes: the hook works only in a data router, that is, when you pass your routes to createBrowserRouter and render the app with <RouterProvider>. Inside a plain <BrowserRouter> it throws the error "useBlocker must be used within a data router".

import { createBrowserRouter, RouterProvider } from 'react-router-dom';

const router = createBrowserRouter([
  { path: '/', element: <MissionControl /> },
  { path: '/configurator', element: <SpaceshipConfigurator /> },
]);

function App() {
  return <RouterProvider router={router} />;
}

Here the routes are described by an array of objects, while page components such as MissionControl stay unchanged. In v8 you import createBrowserRouter and useBlocker from the react-router package, and RouterProvider from react-router/dom.

Now the hook itself. useBlocker accepts a boolean or a function. The function receives an object with the currentLocation, nextLocation and historyAction fields and returns true when the navigation should be stopped. The hook returns a blocker object with a state field: 'unblocked' (nothing is blocked), 'blocked' (navigation is on hold) or 'proceeding' (the confirmed navigation is in progress). In the 'blocked' state, the location field shows where the user wanted to go, and you have two methods: proceed() resumes the navigation, and reset() cancels it and keeps the user where they are.

import { useState } from 'react';
import { useBlocker } from 'react-router-dom';

function SpaceshipConfigurator() {
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
  const [config, setConfig] = useState({});

  // Block only when there are unsaved changes and the path changes
  const blocker = useBlocker(
    ({ currentLocation, nextLocation }) =>
      hasUnsavedChanges && currentLocation.pathname !== nextLocation.pathname
  );

  return (
    <div className="configurator">
      <input
        value={config.shipName ?? ''}
        onChange={(e) => {
          setConfig({ ...config, shipName: e.target.value });
          setHasUnsavedChanges(true);
        }}
        placeholder="Ship name"
      />
      <button onClick={() => setHasUnsavedChanges(false)}>Save</button>

      {blocker.state === 'blocked' && (
        <div className="warning-panel">
          <p>You have unsaved changes. Are you sure you want to leave this page?</p>
          <button onClick={() => blocker.proceed()}>Leave the page</button>
          <button onClick={() => blocker.reset()}>Stay</button>
        </div>
      )}
    </div>
  );
}

The blocker covers clicks on Link, calls to navigate() and the browser's "Back" and "Forward" buttons, and after a click on "Save" the function returns false, so navigation flows freely again. The hook does not display any dialog, so you design the warning panel yourself, in your app's style. There is also unstable_usePrompt, based on window.confirm, but its authors deliberately keep it unstable, because browsers handle window.confirm differently.

useBlocker will not help, however, when the user closes the tab, reloads the page or types a different address into the address bar. In that case the browser unloads the whole page and only the beforeunload event remains. We will handle it in a small custom hook:

import { useEffect } from 'react';

function useBeforeUnloadWarning(when) {
  useEffect(() => {
    if (!when) return;

    const handleBeforeUnload = (e) => {
      e.preventDefault();
      e.returnValue = true; // for older browsers
    };

    window.addEventListener('beforeunload', handleBeforeUnload);
    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };
  }, [when]);
}

In SpaceshipConfigurator you just call useBeforeUnloadWarning(hasUnsavedChanges). The listener exists only while there are unsaved changes, and the cleanup function removes it once the changes are gone. That is what MDN recommends, because in Firefox a page with a beforeunload listener does not go into the bfcache, so returning to it takes longer. The browser shows its own generic message instead of your text, and only if the user has interacted with the page before.

I recommend always combining both mechanisms: useBlocker guards navigation inside the app, and beforeunload guards closing the tab and reloading the page.

The useLocation Hook

The useLocation hook gives us access to the current location object, which contains information about the current URL:

import { useLocation } from 'react-router-dom';

function LocationTracker() {
  const location = useLocation();

  return (
    <div>
      <h2>Current Cosmic Location</h2>
      <p>Path: {location.pathname}</p>
      <p>Query: {location.search}</p>
      <p>Hash: {location.hash}</p>
      <p>Key identifier: {location.key}</p>
      <p>Navigation method: {location.state?.navigationMethod || 'Standard'}</p>
    </div>
  );
}

The location.key field is particularly useful - it is a unique identifier for each entry in the history. We can use it to detect when the user returns to a page they have already visited.

Tracking Navigation History

We can create our own hook for tracking navigation history:

import { useState, useEffect } from 'react';
import { useLocation } from 'react-router-dom';

function useNavigationHistory(maxEntries = 10) {
  const location = useLocation();
  const [history, setHistory] = useState([]);

  useEffect(() => {
    setHistory(prev => {
      // Add current location to history
      const newHistory = [...prev, {
        pathname: location.pathname,
        search: location.search,
        hash: location.hash,
        key: location.key,
        timestamp: Date.now()
      }];

      // Limit history size
      return newHistory.slice(-maxEntries);
    });
  }, [location, maxEntries]);

  return history;
}

// Usage:
function NavigationLogger() {
  const history = useNavigationHistory(5);

  return (
    <div className="navigation-log">
      <h3>Travel Log</h3>
      <ul>
        {history.map((entry, index) => (
          <li key={entry.key}>
            {index === history.length - 1 ? '-> ' : ''}
            {entry.pathname} (visited: {new Date(entry.timestamp).toLocaleTimeString()})
          </li>
        ))}
      </ul>
    </div>
  );
}

Modifying the "Back" Button Behavior

Sometimes we want to change the default behavior of the browser's "Back" button. For example, if the user is on a page that can only be visited after logging in and clicks "Back", we can redirect them to a safe location:

import { useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';

function SecureZone() {
  const navigate = useNavigate();
  const location = useLocation();
  const { isAuthenticated } = useAuth();

  useEffect(() => {
    // Check if the user is logged in on every location change
    if (!isAuthenticated) {
      navigate('/login', { replace: true });
    }

    // Modified "Back" button behavior
    const handlePopState = () => {
      if (!isAuthenticated) {
        // If the user is not logged in and clicks "Back",
        // redirect them to the home page instead of the previous page
        navigate('/', { replace: true });
      }
    };

    window.addEventListener('popstate', handlePopState);

    return () => {
      window.removeEventListener('popstate', handlePopState);
    };
  }, [isAuthenticated, navigate, location]);

  return (
    <div className="secure-zone">
      <h1>Secured Zone</h1>
      <p>Welcome to the Command Center. You have access to classified data.</p>
    </div>
  );
}

Synchronizing History with Global State

In more complex applications, we may want to synchronize browser history with global application state (e.g., Redux):

import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { useDispatch } from 'react-redux';

function HistorySync() {
  const location = useLocation();
  const dispatch = useDispatch();

  useEffect(() => {
    // Every time the location changes, we update the Redux state
    dispatch({
      type: 'navigation/locationChanged',
      payload: {
        pathname: location.pathname,
        search: location.search,
        hash: location.hash,
        state: location.state
      }
    });
  }, [location, dispatch]);

  return null; // Component doesn't render anything
}

// Usage in App:
function App() {
  return (
    <Router>
      <HistorySync />
      {/* Rest of the application */}
    </Router>
  );
}

Analyzing URL Parameters

We often need to analyze query parameters from the URL:

import { useLocation } from 'react-router-dom';

function useParsedQuery() {
  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);

  return {
    get: (param) => queryParams.get(param),
    has: (param) => queryParams.has(param),
    getAll: (param) => queryParams.getAll(param),
    toString: () => queryParams.toString(),
    entries: () => Array.from(queryParams.entries()).reduce((acc, [key, value]) => {
      acc[key] = value;
      return acc;
    }, {})
  };
}

// Usage:
function SpaceshipFilter() {
  const query = useParsedQuery();
  const typeFilter = query.get('type'); // e.g., 'exploration'
  const minCrewSize = query.get('minCrew'); // e.g., '3'

  return (
    <div>
      <h2>Spaceship Filtering</h2>
      {typeFilter && <p>Filtering by type: {typeFilter}</p>}
      {minCrewSize && <p>Minimum crew size: {minCrewSize}</p>}

      {/* Rest of the component */}
    </div>
  );
}

History Stack and Depth Management

Sometimes we want to check how deep in the browser history the user is, or perform an action after reaching a certain depth:

import { useState, useEffect } from 'react';

function useHistoryDepth() {
  const [depth, setDepth] = useState(0);

  useEffect(() => {
    // Set initial depth
    setDepth(window.history.length);

    // Listen for changes
    const handleNavigation = () => {
      setDepth(window.history.length);
    };

    window.addEventListener('popstate', handleNavigation);

    return () => {
      window.removeEventListener('popstate', handleNavigation);
    };
  }, []);

  return depth;
}

// Usage:
function NavigationDepthIndicator() {
  const depth = useHistoryDepth();

  return (
    <div className="depth-indicator">
      <p>History depth: {depth}</p>
      {depth > 10 && (
        <button onClick={() => window.history.go(-5)}>
          Go back 5 pages
        </button>
      )}
    </div>
  );
}

Advanced Scenarios

1. Scroll Restoration

The standard browser behavior is to restore the scroll position when navigating back. In SPA applications, we often need to implement this manually:

import { useEffect, useRef } from 'react';
import { useLocation } from 'react-router-dom';

function useScrollRestoration() {
  const location = useLocation();
  const scrollPositions = useRef({});

  // Save scroll position on location change
  useEffect(() => {
    const saveScrollPosition = (key) => {
      scrollPositions.current[key] = window.scrollY;
    };

    // Save current position when the user leaves the page
    return () => {
      saveScrollPosition(location.key);
    };
  }, [location]);

  // Restore scroll position when the user returns to a page
  useEffect(() => {
    if (scrollPositions.current[location.key] !== undefined) {
      // Restore saved position
      window.scrollTo(0, scrollPositions.current[location.key]);
    } else {
      // New page, scroll to top
      window.scrollTo(0, 0);
    }
  }, [location]);
}

// Usage:
function ScrollRestoringPage() {
  useScrollRestoration();

  return (
    <div className="long-content-page">
      {/* Lots of content causing scrolling */}
    </div>
  );
}

2. Detecting Parameter Changes

Sometimes we need to know if specific URL parameters have changed:

import { useEffect, useRef } from 'react';
import { useLocation } from 'react-router-dom';

function useQueryParamChange(paramName) {
  const location = useLocation();
  const previousParam = useRef(null);

  // Get the current parameter value
  const query = new URLSearchParams(location.search);
  const currentValue = query.get(paramName);

  // Check if the value has changed
  const hasChanged = previousParam.current !== currentValue;

  // Update the ref for the next render
  useEffect(() => {
    previousParam.current = currentValue;
  }, [currentValue]);

  return {
    value: currentValue,
    hasChanged,
    previousValue: previousParam.current
  };
}

// Usage:
function GalaxyFilter() {
  const { value: galaxyType, hasChanged } = useQueryParamChange('galaxy');

  useEffect(() => {
    if (hasChanged) {
      // Perform action on galaxy type change
      console.log(`Filter changed to: ${galaxyType}`);
      // e.g., fetch new data
    }
  }, [galaxyType, hasChanged]);

  return (
    <div>
      {/* Filtering components */}
    </div>
  );
}

Summary

Conscious management of browser history is like keeping a cosmic travel log - it allows us to:

  1. Navigate through time - the user can easily return to visited locations
  2. Control the flow - we can influence how the user moves through the application
  3. Preserve context - state data can be transferred between locations
  4. Optimize the experience - restoring state, scroll position, etc.

Well-designed browser history handling makes the journey through our application intuitive and pleasant, just like a well-planned space mission.

Remember that browser history is not just a navigation mechanism, but also an important element of the user experience. Users expect the "Back" and "Forward" buttons to work intuitively, and your application should respect that.

Code for this lesson: App.jsx
import React, { Suspense, lazy, useState } from 'react';
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';

// Lazy loaded components
const Dashboard = lazy(() => {
  // Simulation of loading delay
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({
        default: () => (
          <div className="page">
            <h1>Dashboard</h1>
            <p>This component was lazily loaded!</p>
            <div className="stats">
              <div className="stat">Users: 1,234</div>
              <div className="stat">Sessions: 5,678</div>
              <div className="stat">Revenue: 9,999 credits</div>
            </div>
          </div>
        )
      });
    }, 1500);
  });
});

const Analytics = lazy(() => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({
        default: () => (
          <div className="page">
            <h1>Analytics</h1>
            <p>Advanced statistics loaded lazily.</p>
            <div className="chart">
              <div className="bar" style={{height: '60%'}}></div>
              <div className="bar" style={{height: '80%'}}></div>
              <div className="bar" style={{height: '45%'}}></div>
              <div className="bar" style={{height: '90%'}}></div>
              <div className="bar" style={{height: '70%'}}></div>
            </div>
          </div>
        )
      });
    }, 2000);
  });
});

const Settings = lazy(() => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({
        default: () => (
          <div className="page">
            <h1>Settings</h1>
            <p>System configuration.</p>
            <div className="settings-list">
              <div className="setting">Dark mode: Enabled</div>
              <div className="setting">Notifications: Enabled</div>
              <div className="setting">Language: English</div>
            </div>
          </div>
        )
      });
    }, 1000);
  });
});

// Loading fallback component
function LoadingSpinner() {
  return (
    <div className="loading">
      <div className="spinner"></div>
      <p>Loading module...</p>
    </div>
  );
}

// Home page (not lazy)
function HomePage() {
  return (
    <div className="page">
      <h1>Home page</h1>
      <p>This page is loaded immediately.</p>
      <p className="info">Click on other links to see lazy loading in action!</p>
    </div>
  );
}

function App() {
  return (
    <BrowserRouter>
      <div className="app">
        <nav>
          <Link to="/">Home (instant)</Link>
          <Link to="/dashboard">Dashboard (1.5s)</Link>
          <Link to="/analytics">Analytics (2s)</Link>
          <Link to="/settings">Settings (1s)</Link>
        </nav>

        <Suspense fallback={<LoadingSpinner />}>
          <Routes>
            <Route path="/" element={<HomePage />} />
            <Route path="/dashboard" element={<Dashboard />} />
            <Route path="/analytics" element={<Analytics />} />
            <Route path="/settings" element={<Settings />} />
          </Routes>
        </Suspense>
      </div>
    </BrowserRouter>
  );
}

export default App;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What information does the useLocation hook provide?

  2. 2. What does calling navigate(-1) do in React Router?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Location tracking

  • Horizontal ordering

    Arrange URL components in the order they appear in an address:

  1. QuestionHook useLocation
  2. Coding taskPractice: useLocation
  3. QuestionuseNavigate with a number
  4. QuestionReplace in navigation
  5. Put in orderURL Structure

Useful articles