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
- 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, useuseElementScrollRestoration:
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.
Troubleshooting
Scroll not restoring
- Ensure
scrollRestoration: truein router config - Check that
data-scroll-restoration-idmatches the ID inuseElementScrollRestoration - Verify the element is scrollable (
overflow: autoorscroll)
Unexpected scroll behavior
- Check for conflicting scroll handlers
- Ensure only one scroll restoration ID per element
- 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