Sub topic 8
Using a Virtualization Library
This chapter assumes you have built the fixed-height virtual list by hand. It also assumes you are comfortable with useRef, useState, and CSS positioning (relative and absolute). Here you replace the hand-written scroll math with TanStack Virtual and learn which options matter and which mistakes to avoid.
Why switch from the hand-written list
The hand-written list works, but it only handles the simplest case. It needs a fixed row height and listens to one scroll element. It does no measuring and has no scroll-to-index support. Each of those features adds code that is easy to get subtly wrong, such as rounding errors, scroll events that arrive out of order, and resize handling.
A virtualization library packages that logic. The one used here is TanStack Virtual, in its React adapter @tanstack/react-virtual. It is headless, which means it renders no markup and applies no styles. It tracks scroll position and sizes, then tells you which rows to render and where to put them. You keep full control of the HTML and CSS.
Install it with npm install @tanstack/react-virtual.
The basic setup
This is the same list as before, built with the useVirtualizer hook.
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>
);
}The structure matches your hand-written version. The outer div scrolls, the inner spacer div has the full list height, and each visible row is absolutely positioned inside the spacer. The library replaces the calculations you wrote yourself.
How the pieces map
| Hand-written list | TanStack Virtual |
|---|---|
| `useState` holding `scrollTop` | Internal state, subscribed to the scroll element |
| `items.length * rowHeight` | `virtualizer.getTotalSize()` |
| `first` and `last` index math | `virtualizer.getVirtualItems()` |
| `top: i * rowHeight` | `v.start`, applied here through `translateY` |
| `rowHeight` constant | `estimateSize` callback, optionally refined by measuring |
| `overscan` prop | `overscan` option |
Each entry in getVirtualItems() is a plain object. These are its fields:
index: the position in your data array. Use it to look up the item.key: a stable identifier for React'skeyprop.start: the pixel offset of the row's top edge from the top of the spacer.size: the row's height in pixels, either estimated or measured.
What happens on each scroll
The diagram shows how one scroll event turns into a new set of rows.
The virtualizer re-renders your component only when the visible range changes. It does not re-render on every scroll pixel.
The options that matter
count
count is the total number of rows. It is the data length, not the number of rows on screen. Change it and the virtualizer recomputes the total size.
getScrollElement
This function returns the DOM element that scrolls. On the first render the ref is still null, because React has not attached it yet. The library handles that and starts observing once the element exists. You do not need an effect for this.
The scroll element does not have to be a div you created. For a list that scrolls with the whole page, TanStack Virtual provides a separate hook, useWindowVirtualizer, which uses the window as the scroll container.
estimateSize
estimateSize receives a row index and returns a height in pixels. For uniform rows, return a constant. For rows of differing but known heights, look the height up from your data:
estimateSize: (index) => (items[index].isHeader ? 48 : 32),When rows have unknown heights, the value is a first guess. The next chapter section on dynamic heights shows how measurement replaces it. A poor guess does not break the list, but it causes the scrollbar to resize as rows are measured.
overscan
overscan is the number of extra rows rendered above and below the visible range. A larger value reduces blank flashes during fast scrolling. It also renders more rows, which costs more on every range change. Values between 3 and 10 suit most lists.
getItemKey
By default, v.key is derived from the row index. That is fine for a list that never reorders. If rows can be inserted, removed, or sorted, supply stable keys from your data:
const virtualizer = useVirtualizer({
count: rows.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 35,
getItemKey: (index) => rows[index].id,
});Without stable keys, React reuses row components by position. Local state, such as an open menu or typed text, then appears on the wrong row after the data changes.
Dynamic row heights
For content-dependent heights, drop the explicit height on the row, add a data-index attribute, and pass measureElement as the row's ref.
import { useRef } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
export function DynamicList({ items }: { items: string[] }) {
const parentRef = useRef<HTMLDivElement>(null);
const virtualizer = useVirtualizer({
count: items.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 50,
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}
data-index={v.index}
ref={virtualizer.measureElement}
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
transform: `translateY(${v.start}px)`,
}}
>
{items[v.index]}
</div>
))}
</div>
</div>
);
}The library reads data-index to know which row it is measuring, then stores the real height. Rows below the measured one shift down, and the total size updates.
Common errors
- Every row renders. The scroll container has no fixed height, so it grows to fit its content. The virtualizer then sees a viewport tall enough for all rows. Give the scroll element a pixel height, or a constrained height from a flex or grid layout, together with
overflow: auto. - Rows stack at the top or overlap. The spacer needs
position: "relative", and each row needsposition: "absolute". Without them,translateYhas nothing to offset from. - Nothing scrolls. The spacer must use
getTotalSize()as its height. If it is missing or zero, the container has no overflow. - State jumps between rows. The row keys are index-based while the data reorders. Use
getItemKeywith a stable id. - The scrollbar jitters with dynamic heights. The estimate is far from the real heights. Choose an
estimateSizeclose to the average measured height. - Measurement never updates. The row is missing
data-index, or the ref is attached to an inner element instead of the absolutely positioned row.
Choosing a library
TanStack Virtual is a good fit when you want to control the markup, need dynamic heights, or want one hook for lists, grids, and horizontal scrolling. Other libraries, such as react-window and react-virtuoso, ship ready-made components. They can be quicker to start with, but you accept their markup and styling. Whichever you pick, the underlying model is the one you built by hand: a scroll container, a spacer, a computed range, and absolutely positioned rows.
Exercise
A teammate converts a list to useVirtualizer, but the page shows all 10,000 rows in the DOM and the list never gets a scrollbar of its own. The scroll div has overflow: auto but no height. What is wrong, and what is the fix?
Show answer
Without a set height, the scroll div grows to fit its content, so the virtualizer sees a viewport as tall as the whole list and treats every row as visible. Give the scroll element a constrained height, for example height: 400 or a height from a flex or grid parent, along with overflow: auto. The virtualizer then sees a small viewport and renders only the rows near it.
Exercise
Rows in a sortable virtual list keep their expanded or collapsed state by position, so after sorting, the wrong rows appear expanded. Which option fixes this, and what should it return?
Show answer
Pass getItemKey to useVirtualizer and return a stable identifier from your data, such as (index) => rows[index].id. Render the row with key={v.key}. React then matches row components to data items rather than to positions.