Sub topic 8
Using a virtualization library
This chapter assumes you can build the fixed-height list from the previous chapters. You should know useState and useRef, CSS position: relative and absolute, and how scroll events work. Here you replace the hand-written scroll math with TanStack Virtual.
Why use a library
The hand-written list works for fixed heights. Real lists add more needs: rows with variable heights, scrolling to an index, resize handling, and horizontal or grid layouts. A library handles these cases and has been tested across browsers.
TanStack Virtual is headless. It gives you numbers (which rows are visible, where each row starts, how tall the list is) and renders no markup. You keep full control of the DOM and styling.
The same list with useVirtualizer
The hook useVirtualizer takes the row count, a function that returns the scroll element, and a size estimate.
import { useRef } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
export function List({ items }: { items: string[] }) {
const parentRef = useRef<HTMLDivElement>(null);
const virtualizer = useVirtualizer({
count: items.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 35,
overscan: 5,
});
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>
);
}Mapping the library to what you built
Each part of the hand-written list has a library counterpart.
| Hand-written version | TanStack Virtual |
|---|---|
| `scrollTop` state and `onScroll` | The hook tracks scroll internally |
| `items.length * rowHeight` | `getTotalSize()` |
| `first` and `last` index math | `getVirtualItems()` |
| `top: i * rowHeight` | `v.start`, used in `translateY` |
| `overscan` constant | `overscan` option |
The structure is unchanged: a scrolling parent, a spacer sized to the full list, and absolutely positioned rows. Only the arithmetic moved into the library.
The virtual item
Each entry from getVirtualItems() has these fields:
index: the position in your data. Use it to look up the item.key: a stable identifier for React'skeyprop. It defaults to the index.start: the pixel offset from the top of the list.size: the row height in pixels.
Positioning with transform
The example moves rows with transform: translateY(...) and leaves top at 0. Changing a transform does not trigger layout, so scrolling stays cheap. Setting top per row also works, as in the hand-written version.
Common errors
- Nothing renders. The scroll element needs a fixed height and
overflow: auto. Without a height, the parent grows to fit the spacer and the list shows no scrolling. - Rows stack at the top. The spacer needs
position: relativeand each row needsposition: absolute. - Wrong scroll element.
getScrollElementmust return the element that actually scrolls. If the ref isnullon first render, the hook retries once the element mounts. - Rows overlap or leave gaps.
estimateSizeis a guess, and rows with different heights need measuring. The next chapter covers this.
Exercise
In the TanStack Virtual example, which two values replace the items.length * rowHeight spacer height and the first/last loop from the hand-written list?
Show answer
virtualizer.getTotalSize() replaces the spacer height, and virtualizer.getVirtualItems() replaces the first/last index calculation and loop.
Exercise
A list renders as an empty box with no scrollbar. The scroll container has overflow: auto but no height. Why does this happen, and how do you fix it?
Show answer
Without a fixed height, the container grows to fit the spacer, so it never overflows and nothing scrolls. Give it a fixed height, such as height: 400.