Does React Router v6 Automatically Restore Scroll Position?
No, React Router v6 does not automatically restore scroll position by default during loader-driven navigation. To enable this behavior, you must explicitly include the <ScrollRestoration /> component within your application's route hierarchy.
How Scroll Restoration Works with Loaders
When using a Data Router (such as createBrowserRouter), the <ScrollRestoration /> component tracks the window's scroll position for each location. In a loader-driven navigation flow, the sequence is as follows:
- The user triggers a navigation event.
- The router executes the associated
loader function.
- Once the loader resolves and the new route renders, the
<ScrollRestoration /> component restores the scroll position associated with that specific location (or scrolls to the top for new entries).
Using preventDefault
Setting the preventDefault prop on the <ScrollRestoration /> component tells the library not to perform the automatic scroll restoration. This allows the application to take full manual control over the scroll position without the library overriding the coordinates during the navigation lifecycle.
Regarding integration with the browser's history.scrollRestoration API: React Router's <ScrollRestoration /> component is designed to manage this logic internally to ensure it synchronizes with the React render cycle and loader resolution, rather than relying solely on the browser's native, often unpredictable, restoration timing.
Implementation and Verification
To implement and verify scroll restoration, ensure you are using a Data Router and place the component in your root layout:
import { ScrollRestoration } from "react-router-dom";
function RootLayout() {
return (
<div>
<Outlet />
<ScrollRestoration />
</div>
);
}
Verification Steps:
- Navigate to a page with significant vertical content.
- Scroll down to a specific section.
- Navigate to a different route.
- Use the browser's "Back" button to return; the page should return to the previously saved scroll position.
Diagnostic Detail Needed: Are you using a Data Router (createBrowserRouter) or the legacy <BrowserRouter> component? <ScrollRestoration /> only functions within Data Routers.