Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 50 ยท Production Concerns

Scroll Restoration, Focus and Page Titles

Restore scroll positions with ScrollRestoration and getKey, move focus and announce page changes for screen readers, and set a document title for every route.

When a normal website changes pages, the browser does a lot of quiet work for free: it loads a new document, scrolls to the top (or restores your position after Back), moves keyboard focus to the start of the page, updates the tab title, and tells screen readers that a new page has loaded. A single-page app swaps content without a page load, so none of that happens unless you do it yourself.

The symptoms are familiar: you click a link at the bottom of a long page and land on the new page already scrolled down; press Back and your place in the list is lost; a keyboard user keeps focus on a link that no longer exists; a screen reader says nothing at all; the browser history shows ten entries all called "My App". This lesson fixes each of them: scroll with ScrollRestoration and getKey, focus and announcements with a small route-change effect, and titles with a per-route <title>. It assumes you know how location and navigation work and have met layout routes.

Scroll restoration

In a data router, add the ScrollRestoration component once, usually in the root layout. It renders nothing visible and manages the window scroll position for every navigation:

JSX
// root.jsx - React Router (read-only)
import { Outlet, ScrollRestoration } from 'react-router';

export default function Root() {
  return (
    <>
      <Header />
      <main>
        <Outlet />
      </main>
      <Footer />
      <ScrollRestoration />
    </>
  );
}

With the defaults, it behaves like a multi-page site:

  • New navigation (a link click or navigate()): scroll to the top, or to the element whose id matches the URL hash if there is one.
  • Back and forward: restore the position you had on that history entry.
  • Reload: positions are kept in sessionStorage, so they survive a refresh in the same tab.
flowchart TD
    A["Navigation completes"] --> B{"Back or forward?"}
    B -->|"yes"| C["Restore the saved position<br/>for that key"]
    B -->|"no"| D{"URL has a hash?"}
    D -->|"yes"| E["Scroll to the element with that id"]
    D -->|"no"| F["Scroll to the top"]

The default key is location.key, which is unique per history entry. That is why a new push never finds a saved position and goes to the top.

ScrollRestoration needs a data router (such as createBrowserRouter); it is not available under plain <BrowserRouter>. In declarative mode, write a small effect instead:

JSX
// scroll-to-top.jsx - React Router declarative mode (read-only)
import { useEffect } from 'react';
import { useLocation } from 'react-router';

export function ScrollToTop() {
  const { pathname, hash } = useLocation();

  useEffect(() => {
    if (hash) {
      document.getElementById(hash.slice(1))?.scrollIntoView();
    } else {
      window.scrollTo(0, 0);
    }
  }, [pathname, hash]);

  return null;
}

This simple version scrolls to the top on every path change, including Back, so it cannot restore positions. If you need restoration without a data router, you have to store positions yourself.

getKey: deciding what counts as "the same page"

getKey receives the location and the matched routes, and returns the key under which a scroll position is stored. Changing it changes when positions are shared:

JSX
// root.jsx - React Router (read-only)
<ScrollRestoration
  getKey={(location, matches) => {
    // same pathname = same scroll position, even via a new link click
    return location.pathname;
  }}
/>

With location.pathname as the key, clicking a link to a page you already visited puts you where you were, instead of at the top. That suits list pages (you return to the same place in a product list) but not articles you want to read from the top, so you can return different keys for different routes, for example location.key for the default behavior in most places and location.pathname for the list.

Two related controls:

  • preventScrollReset on Link, Form and navigate options keeps the current scroll position for a navigation. Use it for tabs, filters and similar changes that update the URL but feel like the same page (see Putting UI State in the URL).
  • Scroll containers other than the window, such as a sidebar or a div with overflow: auto, are not managed by ScrollRestoration. You have to save and restore their scrollTop yourself, which is what the next example does.

Real library or stand-in? The react-router code above is the real API. The live examples use a small hand-written router on React and location.hash. The router stand-in has no history entries and no location.key, so the scroll example behaves like getKey={(location) => location.pathname}: one position per path. Because the preview cannot scroll the whole window, the example scrolls a box inside the page, which is the container case the real component does not handle.

Restoring scroll positions per path

Scroll Article A down about half way, switch to Article B (it starts at the top), scroll it a little, then switch back to A. With the checkbox on, A reappears where you left it and the saved positions line shows both numbers. Turn it off and every switch starts at the top, which is the default behavior for a brand new navigation.

Focus and announcements

Sighted mouse users see that the page changed. Keyboard and screen reader users rely on focus and announcements, and a client-side navigation provides neither. After clicking "Pricing" in the header, focus normally stays on the link you used. A screen reader says nothing, and pressing Tab continues from the header instead of from the new content.

The usual pattern has two parts that run after each navigation (but not on the first load, where the browser already behaves correctly):

  1. Move focus to the new content, either the main region or its heading. The element needs tabIndex={-1} so it can receive focus from code without joining the Tab order.
  2. Announce the new page by putting its title into a visually hidden element with role="status" (a polite live region), which screen readers read out when its text changes.
JSX
// route-change-effects.jsx - React Router (read-only)
import { useEffect, useRef } from 'react';
import { Outlet, useLocation } from 'react-router';

export default function Layout() {
  const { pathname } = useLocation();
  const mainRef = useRef(null);
  const isFirstRender = useRef(true);

  useEffect(() => {
    if (isFirstRender.current) {
      isFirstRender.current = false;
      return;
    }
    mainRef.current?.focus();
  }, [pathname]);

  return (
    <>
      <a href="#content" className="skip-link">Skip to main content</a>
      <Header />
      <main id="content" ref={mainRef} tabIndex={-1}>
        <Outlet />
      </main>
    </>
  );
}
flowchart LR
    A["Link clicked"] --> B["URL and content change<br/>(no page load)"]
    B --> C["Effect: focus the main region"]
    B --> D["Effect: set document.title"]
    D --> E["Live region announces the new title"]

What the browser would do for a real page load, rebuilt by hand: focus, title and an announcement.

A few details matter. Focusing the whole <main> makes some screen readers read all of its text, so many teams focus the page's <h1> instead (give it tabIndex={-1} and a ref, for example from a useEffect in each page, or have the layout query main h1). Remove the focus ring only on those programmatic targets, never on links and buttons. Keep a skip link as the first focusable element so keyboard users can jump past the header on every page. The framework Next.js ships a route announcer for you; React Router leaves this to the app, so it is worth adding once in the root layout.

Document titles

The page title is shown in the browser tab, in history and bookmarks, in search results, and it is the first thing a screen reader says when a page opens. Every route should set its own. Options, from simplest to most structured:

  • A <title> element in the route component. React 19 hoists a <title> rendered anywhere in the tree into the document head, so each route component can write <title>Pricing - My App</title> and it just works.
  • A title in the route's handle, read by the root layout through useMatches() and applied in one place. This is covered in Route Handles and Breadcrumbs, and it keeps all titles in the route config.
  • Framework mode: each route module exports a meta function that also covers description and social tags (see Server Loaders, Client Loaders and Actions).
JSX
// pricing.jsx - React 19 + React Router (read-only)
export default function Pricing() {
  return (
    <>
      <title>Pricing - My App</title>
      <h1>Pricing</h1>
      <p>Three plans, one price per seat.</p>
    </>
  );
}

Put the specific part first ("Pricing - My App") so it is not cut off in a narrow tab, and make titles unique per page.

The next example puts focus, announcement and title together, with a switch to turn the behavior off so you can feel the difference.

Focus, announcement and title on navigation

Switch between the pages with the box ticked: the browser tab title changes, focus moves to #content, and the live region receives "Navigated to ..." text. Untick it and use the links again: focus stays on whatever you last focused (usually the link you clicked) and the "screen reader" stays silent. Keyboard users get the second experience in every app that skips this step.

Focus management can annoy as much as help. Do not move focus for navigations that feel like the same page, such as switching a tab or changing a filter in the URL. Do it for real page changes.

Putting it together

For a typical data-mode app, the root layout holds four things: ScrollRestoration, a skip link, a <main tabIndex={-1}> that receives focus after navigations, and a live region. Each route component sets its own title. That handful of lines gives your app the baseline behavior users already expect from the web.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the default ScrollRestoration do when a user clicks a normal link to a new page?

    A new navigation has a fresh location.key, so there is no saved position. The router scrolls to the top, or to the element whose id matches the hash.
  2. 2. What does getKey={(location) => location.pathname} change?

    The key decides which visits share a saved position. Using the pathname makes every visit to the same path share one, instead of one per history entry.
  3. 3. Why does a client-side navigation need explicit focus management for accessibility?

    The browser's built-in behavior comes from loading a new document. A single-page app swaps content in place, so you must move focus and announce the change.
  4. 4. A heading or main element must be focusable by code but not appear in the Tab order. Which attribute does that?

    tabIndex -1 allows element.focus() from JavaScript without adding the element to the keyboard Tab sequence.
  5. 5. You change a ?tab= search param to switch tabs and do not want the page to jump to the top. What should you use?

    preventScrollReset keeps the current scroll position for navigations that feel like the same page.

Summary

  • A single-page app must recreate what page loads give for free: scroll position, focus, announcements and titles.
  • ScrollRestoration (data routers) scrolls to the top on new navigations, to the hash target when there is one, and restores positions on Back and forward; getKey chooses what shares a position and preventScrollReset skips the reset.
  • Scroll containers other than the window need manual handling; declarative mode needs your own effect.
  • After navigations, move focus to a tabIndex={-1} main region or heading and update a polite live region; skip the first render and same-page navigations.
  • Give every route its own title with a React 19 <title>, route handle data or the framework's meta export.

Next: Route Handles and Breadcrumbs