日本語

How to Restore Scroll Position on Back Navigation in React Router

​​React​React Router,TypeScript

In React Router's data mode, placing a single <ScrollRestoration /> is enough to restore the scroll position you left when you go back to a previous page with the Back button. When you move to a new page by a link, it is shown from the top.

In a test environment, I built a list of 60 cats and a cat page. I scrolled the list down, opened a cat page, and went back with the Back button. I recorded window.scrollY with and without ScrollRestoration.

Note

The test environment was Ubuntu 24.04, Node.js 22.22.0, and Chromium 153 (Chrome for Testing 153.0.8010.12). I used react-router 8.5.0, react / react-dom 19.3.1, @types/react 19.3.0, and typescript 7.0.2. I set the screen size to 400×700px. Instead of a real server, the data came from a function that returned after a 300-millisecond wait. I ran the code transpiled with esbuild (a development build) in Chromium and operated it with Playwright.

Place one ScrollRestoration in the outermost route

According to the ScrollRestoration reference, this component reproduces, for page transitions inside the app, the scroll position restoration that the browser normally performs. You place only one in the app. It works in data mode and framework mode, not in declarative mode with <BrowserRouter> (list of APIs available per mode).

In data mode, place it in the component of the outermost route of the router created with createBrowserRouter, and it renders on every page. The code I used for the test is below. I omitted the part that switches placement for testing, and I changed the import paths to match the file locations.

tsx
// main.tsx
import { createRoot } from 'react-dom/client';
import { createBrowserRouter } from 'react-router';
import { RouterProvider } from 'react-router/dom';
import { CatList, CatPage, Root, catLoader, catsLoader } from './routes';

const router = createBrowserRouter([
  {
    path: '/',
    Component: Root,
    HydrateFallback: () => <p>読み込み中…</p>,
    children: [
      { path: 'cats', loader: catsLoader, Component: CatList },
      { path: 'cats/:catId', loader: catLoader, Component: CatPage },
    ],
  },
]);

createRoot(document.getElementById('root')!).render(<RouterProvider router={router} />);
tsx
// routes.tsx (partial)
import { Link, Outlet, ScrollRestoration, useLoaderData } from 'react-router';
import { fetchCats } from './api';

export function Root() {
  return (
    <div>
      <header>
        <Link to="/cats">一覧へ</Link>
      </header>
      <Outlet />
      <ScrollRestoration />
    </div>
  );
}

export async function catsLoader() {
  return { cats: await fetchCats() };
}

export function CatList() {
  const { cats } = useLoaderData<typeof catsLoader>();
  return (
    <ul>
      {cats.map((cat) => (
        <li key={cat.id} style={{ height: 80 }}>
          <Link to={`/cats/${cat.id}`}>{cat.name}</Link>
        </li>
      ))}
    </ul>
  );
}

In framework mode, as described in the migration guide from RouterProvider, you place it in the Layout of root.tsx, just before <Scripts />. I only tested data mode in this article.

When I placed it inside a <BrowserRouter> in declarative mode, the test environment threw the error below, and nothing was displayed on the screen.

text
uncaught: useMatches must be used within a data router.  See https://reactrouter.com/en/main/routers/picking-a-router.

Compare the position on return with and without the component

I scrolled the list (about 4,850px tall) until scrollY was 2000, then clicked a cat link visible there. I opened the cat page, scrolled to the top to read it, and returned to the list with the browser's Back button.

Without ScrollRestoration, when the cat page was long, it opened at scrollY 2000 rather than at the top. React Router does not change the scroll position on link navigation.

The position after going back depended on the length of the cat page. When the cat page was long, about 2,900px, the list returned to 2000. When I shortened the cat page to the screen height (700px), the list returned to the very top (0).

Horizontal bar chart. Before leaving the list, it was scrolled to 2000px. With ScrollRestoration (both long and short cat pages), it returns to 2000px. Without ScrollRestoration (long cat page), it returns to 2000px. Without ScrollRestoration (short cat page), it returns to 0px (top)
scrollY after returning to the list with the Back button. Without ScrollRestoration, the position is lost when the cat page is short

Without ScrollRestoration, history.scrollRestoration was auto. As MDN explains, with auto the browser tries to restore the position on history navigation, not React Router. However, in the Chromium of this test environment, as shown above, the list position was not restored when the cat page was short. I did not test other browsers.

With ScrollRestoration, history.scrollRestoration became manual. React Router restores the position instead of leaving it to the browser. Cat pages opened from the top regardless of length, and when returning, the list went back to 2000 in both cases.

The position is restored after the loader finishes

After pressing Back, I recorded the visible page and scrollY every 50 milliseconds (with ScrollRestoration, long cat page). I omitted the two lines at +455ms and +509ms.

text
戻るを押した後:
  + 14ms 表示=詳細 scrollY=0
  + 70ms 表示=詳細 scrollY=0
  +123ms 表示=詳細 scrollY=0
  +180ms 表示=詳細 scrollY=0
  +235ms 表示=詳細 scrollY=0
  +290ms 表示=詳細 scrollY=0
  +345ms 表示=一覧 scrollY=2000
  +400ms 表示=一覧 scrollY=2000
戻った後: /cats scrollY=2000

While catsLoader for the list was loading, for about 300 milliseconds, the cat page stayed displayed at the top (0). When the list was rendered, the position returned to 2000 at the same time. The position was never restored too early, on a short list before the data arrived.

Point

ScrollRestoration restores the scroll position after the loader finishes and the new page is rendered. Even when the list reloaded its data on return, the position was not lost.

The position survives a page reload

I scrolled the list to 1500 and reloaded the page. After the reload, the list was still displayed at 1500. At that time, sessionStorage contained this value:

text
sessionStorage["react-router-scroll-positions"] = {"default":1500}

As the reference says, positions are saved in sessionStorage under react-router-scroll-positions. You can change the name with storageKey. default is the value of the key used to remember a position (location.key). It is used when the history has no React Router key yet, such as for a page opened directly by URL (lib/router/history.ts).

Note

Reading the installed React Router 8.5.0 code and the source on GitHub (lib/dom/lib.tsx), what is saved and restored is window.scrollY, that is, the scroll position of the whole page. I read it as not covering the position of a scrollable element inside the page. I did not test such elements in this environment.

Use getKey to restore the position on link navigation to the same path

By default, positions are remembered per history entry (location.key). So when I moved to the list with the link to the list at the top of a cat page, that was a new navigation rather than a Back, and the list was displayed from the top (0).

If you want the position restored even for link navigation to the same path, return location.pathname from getKey.

tsx
<ScrollRestoration getKey={(location) => location.pathname} />

With this, the list displayed at 2000 even when I moved to it with the link at the top of the cat page. The reference also says that using only the pathname restores the position when you later navigate to a path you opened before.

Add preventScrollReset to keep the position when clicking a tab in the middle of a page

Once ScrollRestoration is placed, a new navigation takes the page to the top. For navigation such as switching tabs with a query string, returning to the top can be a problem.

In the test, I put links to ?tab=meals in the middle of a cat page (about 1,200px from the top). For comparison, I also placed one link without preventScrollReset.

tsx
<nav className="tabs">
  <Link to="?tab=profile" preventScrollReset>
    プロフィール
  </Link>
  <Link to="?tab=meals" preventScrollReset>
    ごはん
  </Link>
  <Link to="?tab=meals" className="no-prevent">
    ごはん(preventScrollReset なし)
  </Link>
</nav>

When I clicked at scrollY 1000, the link with preventScrollReset stayed at 1000, and the link without it went to 0.

text
preventScrollReset あり: 押す前 scrollY=1000 → 押した後 /cats/1?tab=meals scrollY=1000
preventScrollReset なし: 押す前 scrollY=1000 → 押した後 /cats/1?tab=meals scrollY=0

According to the Link reference, preventScrollReset only stops the reset to the top on a new navigation. Position restoration on Back and Forward still happens. When navigating with useNavigate, write navigate('?tab=meals', { preventScrollReset: true }), as described in the useNavigate reference.

​Posted by 86