TanStack Router scrollRestoration Deep Dive - From Source Code to Implementation
In modern Single Page Application (SPA) development, user experience optimization often lies in the attention to detail. Among these, scroll position restoration is a feature that appears simple but is highly technical. This article will thoroughly analyze the implementation principles of TanStack Router’s scrollRestoration feature, from basic concepts to source code analysis, providing a comprehensive understanding of this important functionality.
scrollRestoration is a configuration option provided by TanStack Router that controls the behavior of scroll position restoration. When set to true, it will:
Automatically save scroll position: Save the current scroll position when the user leaves a page
Automatically restore scroll position: Restore to the previous scroll position when the user returns to a page
Enhance user experience: Avoid users having to re-scroll to their previous browsing position after navigation
Use Case Examples
E-commerce Website Scenario
Consider a user browsing a product listing page:
Without scrollRestoration:
User scrolls to the 50th product position
Clicks on a product to enter the detail page
Clicks browser back button to return to listing page
Page returns to the top, user needs to scroll again to find the 50th product 😫
With scrollRestoration enabled:
User scrolls to the 50th product position
Clicks on a product to enter the detail page
Clicks browser back button to return to listing page
Page automatically scrolls to the 50th product position 😊
Other Application Scenarios
Social Media Feed: Scroll to the 100th post, click on comments and return, still at the 100th post position
Document Reading: In the middle of a long document, click a link and return, still at the original reading position
Search Results: View an item on page 3 of search results, return and still on page 3
exportinterfaceRouterOptions<...> { /** * If `true`, scroll restoration will be enabled * @defaultfalse */ scrollRestoration?: boolean
/** * A function that will be called to get the key for the scroll restoration cache. * @default (location) => location.href */ getScrollRestorationKey?: (location: ParsedLocation) =>string /** * The default behavior for scroll restoration. * @default 'auto' */ scrollRestorationBehavior?: ScrollBehavior /** * An array of selectors that will be used to scroll to the top of the page in addition to `window` * @default ['window'] */ scrollToTopSelectors?: Array<string | (() =>Element | null | undefined)> }
3. Scroll Restoration Setup in Router Initialization
// Throttle scroll events, trigger at most once every 100ms if (typeofdocument !== 'undefined') { document.addEventListener('scroll', throttle(onScroll, 100), true) }
// Listen to route rendering completion event, restore scroll position router.subscribe('onRendered', (event) => { const cacheKey = getKey(event.toLocation)
if (!router.resetNextScroll) { router.resetNextScroll = true return }
Note over User: User Browsing and Navigation User->>Browser: Scroll page Browser->>Router: scroll event Router->>Storage: Save scroll position { x, y } User->>Router: Click link navigation Router->>Storage: Save current page scroll position Router->>Browser: Navigate to new page Note over User: User Return Operation User->>Browser: Click back button Browser->>Router: Route change event Router->>Storage: Read saved scroll position Router->>Router: Wait for page rendering completion Router->>Browser: window.scrollTo(x, y) Browser->>User: Page scrolls to previous position
Advanced Features
1. Multi-element Scroll Support
TanStack Router supports not only window-level scrolling, but also scrolling containers within the page:
1 2 3 4 5 6 7 8 9
// Support multiple scroll elements const elementSelector = event.target === window ? 'window' : getCssSelector(event.target)
// Set scroll restoration ID for specific elements <div data-scroll-restoration-id="product-list" className="overflow-auto"> {/* Scrolling content */} </div>
TanStack Router’s scrollRestoration feature achieves precise scroll position restoration through the following key technologies:
Browser API Takeover: Takes control of native browser behavior through history.scrollRestoration = 'manual'
Event Listening Mechanism: Monitors scroll events and saves scroll positions in real-time
SessionStorage Persistence: Uses sessionStorage to save scroll data across pages
Smart Restoration Strategy: Combines requestAnimationFrame and retry mechanisms to ensure accurate restoration
Performance Optimization: Optimizes performance through throttling, ignore mechanisms, etc.
Multi-element Support: Supports not only window scrolling but also scrolling containers within pages
This feature appears simple, but its implementation involves deep understanding of browser APIs, event handling optimization, data persistence strategies, and multiple technical layers. Through source code analysis, we can see the TanStack Router team’s meticulous consideration and technical depth in user experience optimization.
For modern SPA applications, enabling scrollRestoration: true is a simple yet effective user experience enhancement solution. It not only has sophisticated technical implementation, but more importantly, it truly solves the pain point problem users encounter when navigating within applications.