Skip to main content

useScrollRestoration

When rendered inside a RouterProvider, will restore scroll positions on navigations.

Parameters

object
GetScrollRestorationKeyFunction
A function that returns a key to use for scroll restoration. This is useful for custom scroll restoration logic, such as using only the pathname so that subsequent navigations to prior paths will restore the scroll.Defaults to location.key.
string
default:"\"react-router-scroll-positions\""
The key to use for storing scroll positions in sessionStorage.

Type Declaration

Deprecation Notice

This hook is deprecated in favor of the <ScrollRestoration> component. The component approach is preferred because:
  1. Better SSR support: The component can inject the necessary script for SSR scroll restoration
  2. Simpler API: No need to manually call the hook in your components
  3. Automatic setup: Just render the component and it works

Migration Guide

Before (using useScrollRestoration)

After (using ScrollRestoration component)

Usage Examples (Legacy)

Basic Usage

Custom Storage Key

Pathname-Based Restoration

Route-Based Restoration

Conditional Restoration

How It Works

The hook:
  1. Saves scroll positions to sessionStorage when navigating away from a page
  2. Restores scroll positions when navigating back to a previously visited page
  3. Uses location.key by default to track scroll positions for each history entry
  4. Allows customization via the getKey function for different restoration strategies

Alternatives

Manual Scroll Management

Notes

  • Deprecated: Use the <ScrollRestoration> component instead
  • Available in Framework and Data modes only
  • Must be used within a RouterProvider
  • Stores scroll positions in sessionStorage
  • The getKey function allows customizing which navigations restore scroll
  • Returning null from getKey prevents scroll restoration for that navigation