Sub topic 11
Scrolling to a row and restoring position
This chapter assumes you have built the fixed-height virtual list from earlier chapters. You should know how the scroll container, the spacer, and the visible range work. You should also be comfortable with useRef, useEffect, and the useVirtualizer hook from TanStack Virtual.
Virtualization removes most rows from the DOM. That breaks two things users expect: jumping to a specific row, and coming back to the place they left. Both need to be rebuilt from the scroll offset instead of from DOM elements.
Why you cannot just call scrollIntoView
In a normal list you would find the row's element and call element.scrollIntoView(). In a virtual list, a row far from the viewport has no element. There is nothing to find.
The fix is to turn the problem into arithmetic. A row's position is a number, so you scroll the container to that number. The row then enters the visible range on the next render.
For a fixed-height list, the offset of row i is i * rowHeight. That is the same value you already use for the top style.
Scrolling to an index in a hand-written list
Set scrollTop on the scroll container. The existing onScroll handler then updates state, the visible range recalculates, and the target row renders.
import { useRef, useState } from "react";
const ROW_HEIGHT = 35;
const HEIGHT = 400;
const OVERSCAN = 3;
export function JumpList({ items }: { items: string[] }) {
const scrollerRef = useRef<HTMLDivElement>(null);
const [scrollTop, setScrollTop] = useState(0);
const first = Math.max(0, Math.floor(scrollTop / ROW_HEIGHT) - OVERSCAN);
const last = Math.min(
items.length - 1,
Math.ceil((scrollTop + HEIGHT) / ROW_HEIGHT) + OVERSCAN
);
function jumpTo(index: number) {
const el = scrollerRef.current;
if (!el) return;
const centered = index * ROW_HEIGHT - (HEIGHT - ROW_HEIGHT) / 2;
el.scrollTo({ top: Math.max(0, centered) });
}
const rows = [];
for (let i = first; i <= last; i++) {
rows.push(
<div
key={i}
style={{
position: "absolute",
top: i * ROW_HEIGHT,
left: 0,
right: 0,
height: ROW_HEIGHT,
}}
>
{items[i]}
</div>
);
}
return (
<div>
<button onClick={() => jumpTo(5000)}>Go to row 5000</button>
<div
ref={scrollerRef}
style={{ height: HEIGHT, overflow: "auto" }}
onScroll={(e) => setScrollTop(e.currentTarget.scrollTop)}
>
<div style={{ height: items.length * ROW_HEIGHT, position: "relative" }}>
{rows}
</div>
</div>
</div>
);
}The code never touches a row element. It sets one number on the container. The browser clamps values that are too large or negative, so a jump to the last row does not overshoot.
Alignment
Where the target row lands in the viewport is a choice. Three alignments cover most cases:
| Alignment | Target offset | Typical use |
|---|---|---|
| start | `index * rowHeight` | "Back to top" buttons, jumping to a section header |
| center | `index * rowHeight - (height - rowHeight) / 2` | Search results, where context above and below helps |
| end | `(index + 1) * rowHeight - height` | Scrolling to the newest item in a chat |
There is also an "auto" behavior. It scrolls only if the row is not already visible, and only as far as needed. Use it for keyboard navigation, where moving by one row should not jump the viewport.
Scrolling with TanStack Virtual
The library does this arithmetic for you, including for variable heights. The virtualizer instance has two methods for it:
scrollToIndex(index, options)scrolls to a row. Options includealign("start","center","end", or"auto") andbehavior("auto"or"smooth").scrollToOffset(px, options)scrolls to a raw pixel offset.
With dynamic heights, the offset of a row you have not rendered yet is only an estimate. The library uses your estimateSize values for unmeasured rows. As the target area renders, rows get measured and the true offset shifts. The library re-checks and corrects its position after the jump, but this has consequences:
- A jump can visibly adjust by a few pixels, or by more if your estimates are poor.
behavior: "smooth"over a long distance can end in the wrong place, because the target moves while the animation runs. Prefer instant jumps for long distances. Use smooth scrolling only for short moves.- A good
estimateSizemakes jumps land accurately on the first attempt.
Restoring position after navigation
A common scenario: the user scrolls a long list, opens a detail page, and presses Back. The list component unmounted, so its scroll position is gone. Without restoration the user starts at the top and loses their place.
The approach has two parts:
- Save the scroll offset while the user scrolls.
- When the list mounts again, tell the virtualizer to start from the saved offset.
The initialOffset option sets the starting offset, so the first render already shows the right rows. You do not need to scroll after mounting, and the user never sees the top of the list flash by.
import { useRef } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
const STORAGE_KEY = "inbox-scroll-offset";
function readSavedOffset(): number {
const raw = sessionStorage.getItem(STORAGE_KEY);
const parsed = raw === null ? 0 : Number(raw);
return Number.isFinite(parsed) ? parsed : 0;
}
export function RestoringList({ items }: { items: string[] }) {
const parentRef = useRef<HTMLDivElement>(null);
const virtualizer = useVirtualizer({
count: items.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 35,
overscan: 5,
initialOffset: readSavedOffset(),
});
return (
<div>
<button onClick={() => virtualizer.scrollToIndex(0, { align: "start" })}>
Back to top
</button>
<div
ref={parentRef}
style={{ height: 400, overflow: "auto" }}
onScroll={(e) =>
sessionStorage.setItem(STORAGE_KEY, String(e.currentTarget.scrollTop))
}
>
<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>
);
}Writing to sessionStorage on every scroll event is cheap for a single number. If you also run heavy work in the handler, throttle it. Use sessionStorage when the position should survive navigation within a tab. Use localStorage only if you want it to survive closing the tab, which is rarely what users expect.
Restoration pitfalls
- Data is not there yet. If the list loads from a server,
items.lengthmay be0on the first render. The total size is then0, and the browser clamps the offset to0. Delay mounting the virtualized list until the data is available, or restore after the data arrives. - Stale offsets. If the data changed while the user was away, row 800 may now be a different item. Pixel offsets are only reliable when the list is the same. For lists that change, save an anchor instead: the id of the first visible item. On return, find that item's index and call
scrollToIndex. - Heights differ between visits. With dynamic heights, a saved pixel offset corresponds to the measured heights from last time. After remounting, measurements are gone and estimates are used. The restored view can then show slightly different rows. An anchor id with
scrollToIndexis more robust here. - Width changes. If the window was resized in between, wrapped text changes row heights. The same argument applies: prefer an anchor.
- Router scroll handling. Many routers try to restore window scroll on their own. They know nothing about your inner scroll container, so they will not help. Make sure they do not scroll the page to the top and fight your restoration.
Saving an anchor instead of a pixel offset
To save an anchor, read the first visible item from the virtualizer. getVirtualItems() returns rows including overscan, so the first entry may sit above the viewport. Use the item at the start of the visible range instead. The range property gives startIndex and endIndex without overscan:
const startIndex = virtualizer.range?.startIndex ?? 0;
const anchorId = items[startIndex].id;Store anchorId. On the next mount, look up its new index with items.findIndex and call scrollToIndex once the list has mounted. This variant needs an effect, because the target depends on measured rows. A brief flash from the top is possible, so hide the list or accept the adjustment.
Common mistakes
- Calling
scrollToIndexbefore the scroll element exists. InsideuseEffect, check that the ref is set. - Using
scrollToIndexwith an index outside0tocount - 1. Clamp it first. - Treating overscan rows as visible when saving an anchor.
- Expecting smooth scrolling to be exact on long, dynamically measured lists.
Exercise
A list with variable row heights saves scrollTop in sessionStorage and passes it as initialOffset after the user navigates back. The restored list shows slightly different rows than the user left. Give two causes and one fix.
Show answer
Causes: the data changed while the user was away, so the same pixel offset points at different items. Or the remounted list uses estimated heights instead of the earlier measured heights, so the same offset maps to different rows. Fix: save an anchor, such as the id of the first visible item, and on return find its index and call scrollToIndex.
Exercise
In a fixed-height list, row height is 40 px and the viewport is 400 px tall. What scrollTop places row 100 at the center of the viewport?
Show answer
Row 100 starts at 100 * 40 = 4000 px. To center it, subtract (400 - 40) / 2 = 180 px. The answer is 3820 px.