Sub topic 11
Scrolling to a Row and Restoring Position
This chapter assumes you can build a fixed-height virtual list and use useVirtualizer from TanStack Virtual. It also assumes you know useRef and useEffect.
In a normal list you can call element.scrollIntoView() on any row. In a virtual list that fails, because most rows are not in the DOM. You have to scroll by index and let the list render the row afterward.
Scrolling to an index
TanStack Virtual provides scrollToIndex. It computes the row's offset, sets the scroll position on the scroll element, and the visible range then updates on its own.
import { useRef } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
export function JumpList({ items }: { items: string[] }) {
const parentRef = useRef<HTMLDivElement>(null);
const virtualizer = useVirtualizer({
count: items.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 35,
overscan: 5,
});
return (
<div>
<button onClick={() => virtualizer.scrollToIndex(500, { align: "center" })}>
Jump to row 500
</button>
<div ref={parentRef} style={{ height: 400, overflow: "auto" }}>
<div style={{ height: virtualizer.getTotalSize(), position: "relative" }}>
{virtualizer.getVirtualItems().map((v) => (
<div
key={v.key}
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: v.size,
transform: `translateY(${v.start}px)`,
}}
>
{items[v.index]}
</div>
))}
</div>
</div>
</div>
);
}The align option accepts "start", "center", "end" and "auto". With "auto", the list does not move if the row is already visible.
For a hand-written fixed-height list, the offset is simple arithmetic. Set scrollTop on the scroll container to index * rowHeight.
containerRef.current?.scrollTo({ top: index * rowHeight });Why dynamic heights make this harder
With measured rows, rows you have not rendered still use the estimateSize guess. If you jump to row 500, the library scrolls to an estimated offset. The rows then render and are measured, and the real offset differs from the estimate. The target row can end up off screen.
TanStack Virtual handles this by checking the position again after measuring and correcting it for a short period. You can help by keeping estimateSize close to the average real height. A poor estimate causes visible corrections.
Restoring scroll position
When a user opens a detail page and comes back, a list that remounts starts at the top. To restore the position, save the scroll offset before the list unmounts and pass it back as initialOffset.
import { useEffect, useRef } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
let savedOffset = 0;
export function RestoringList({ items }: { items: string[] }) {
const parentRef = useRef<HTMLDivElement>(null);
const virtualizer = useVirtualizer({
count: items.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 35,
initialOffset: savedOffset,
});
useEffect(() => {
return () => {
savedOffset = virtualizer.scrollOffset ?? 0;
};
}, [virtualizer]);
return (
<div ref={parentRef} style={{ height: 400, overflow: "auto" }}>
<div style={{ height: virtualizer.getTotalSize(), position: "relative" }}>
{virtualizer.getVirtualItems().map((v) => (
<div
key={v.key}
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: v.size,
transform: `translateY(${v.start}px)`,
}}
>
{items[v.index]}
</div>
))}
</div>
</div>
);
}The module variable is the simplest store. In a real app you might use a router's state, sessionStorage, or a state library. Key the saved value by list identity if the app has several lists.
Common errors
- Calling
scrollIntoViewon a row that is not rendered. The element does not exist yet, so usescrollToIndex. - Restoring an offset before data has loaded. If
countis 0, the spacer has no height and the browser clamps the scroll position to 0. - Saving the offset only in a scroll handler without throttling. This causes many writes. Read it once on unmount instead.
- Restoring a pixel offset after the data changed. The same offset may now show different rows. Saving an index and using
scrollToIndexis safer in that case.
Exercise
A user returns to a list with dynamic row heights after the item data was refreshed from the server. Why might restoring a saved pixel offset show the wrong rows, and what could you save instead?
Show answer
Pixel offsets depend on the heights and order of the rows above the viewport. If the data changed, those rows differ, so the same offset can land on other content. Save the index (or the item's ID) of the first visible row and restore it with scrollToIndex after the data loads.