Scroll Restoration and Jump-to-Index
What you'll learn: How to programmatically navigate to specific items in virtualized lists and preserve scroll positions across navigations.
Virtualization introduces a challenge: when users navigate away and return, or when data updates, their scroll position is often lost. Additionally, you may need to jump directly to a specific item (like a search result or highlighted row) without the user manually scrolling.
The Core Problem
Imagine reading a long article, bookmarking your place, then returning to find yourself at the top again—frustrating! Virtualized lists face this because React unmounts components that scroll out of view. Without intervention, the browser has no "memory" of where the user was.
scrollToIndex: Direct Navigation
TanStack Virtual provides a scrollToIndex method on the virtualizer instance. This programmatically scrolls to any item by its index:
const virtualizer = useVirtualizer({
count: 10000,
getScrollElement: () => parentRef.current,
estimateSize: () => 50
});
// Jump to item 500
virtualizer.scrollToIndex(500);
This is perfect for "jump to search result" or "scroll to selected item" features.
Scroll Restoration Strategy
Preserve scroll position by storing the scrollOffset before unmounting and restoring it on mount:
// Before navigation
const currentScroll = virtualizer.scrollOffset;
sessionStorage.setItem('listScroll', currentScroll);
// After return
useEffect(() => {
const savedScroll = sessionStorage.getItem('listScroll');
if (savedScroll) {
virtualizer.scrollToOffset(parseInt(savedScroll));
}
}, []);
Key Takeaway: Use scrollToIndex() for programmatic navigation to specific items and scrollToOffset() combined with stored values to restore scroll positions, ensuring virtualized lists maintain user context across updates and route changes.