Skip to main content

Scroll Restoration

Scroll restoration ensures that when users navigate back and forth between pages, the scroll position is restored to where they left off. TanStack Router provides both automatic and manual scroll restoration.

Overview

Scroll restoration helps maintain a native-like browsing experience by:
  • Restoring scroll position when navigating back
  • Scrolling to top on new page navigation
  • Supporting custom scroll containers
  • Working with virtualized lists

Automatic Scroll Restoration

Enable scroll restoration globally in your router:
src/main.tsx
With this enabled:
  • Forward navigation: Scrolls to top
  • Back/forward navigation: Restores previous scroll position
  • Same page navigation: Maintains scroll position

Disable Scroll Reset

Prevent scrolling to top for specific links:

Manual Scroll Restoration

For custom scroll containers, use useElementScrollRestoration:
src/routes/by-element.tsx

Virtualized Lists

Restore scroll position in virtualized lists using TanStack Virtual:

Complete Example

Here’s a full example from the TanStack Router source:
src/routes/scroll-demo.tsx

Multiple Scroll Containers

Handle multiple scrollable areas on one page:

Smooth Scrolling

Enable smooth scrolling in CSS:

Hash Navigation

Scroll to anchors using hash:

Scroll to Top Button

Implement a scroll to top button:

Best Practices

Enable Globally

Turn on scroll restoration at the router level for consistent behavior

Unique IDs

Use descriptive, unique IDs for each scroll container

Test Navigation

Test both forward and back navigation to ensure proper restoration

Consider UX

Use resetScroll= sparingly - users expect to scroll to top on new pages
Performance: Scroll restoration adds minimal overhead and significantly improves user experience.
Dynamic Content: If your page content changes dynamically, scroll positions may not restore perfectly. Consider using virtualization for large lists.

Troubleshooting

Scroll not restoring

  1. Ensure scrollRestoration: true in router config
  2. Check that data-scroll-restoration-id matches the ID in useElementScrollRestoration
  3. Verify the element is scrollable (overflow: auto or scroll)

Unexpected scroll behavior

  1. Check for conflicting scroll handlers
  2. Ensure only one scroll restoration ID per element
  3. Verify CSS doesn’t prevent scrolling

Next Steps

Code Splitting

Optimize bundle size while maintaining scroll restoration

SSR

Handle scroll restoration in server-side rendered apps