Sub topic 9
Variable and dynamically measured row heights
This chapter assumes you have built the fixed-height list from earlier in this tutorial. You should know how the spacer, absolute positioning, and visible-range calculation work. You should also be comfortable with useRef and basic @tanstack/react-virtual usage.
Why fixed heights stop working
The hand-written list computes the first visible row with scrollTop / rowHeight. That works only when every row has the same height. Chat messages, comments, and cards with wrapped text have heights that depend on their content, and you cannot know them until the browser lays them out.
A virtualizer therefore needs an offset for every row, and each offset is the sum of the heights of all rows above it. For rows that have not rendered yet, it has no measured height. It uses a guess instead.
Estimate first, then measure
TanStack Virtual handles this in two steps:
estimateSizereturns a guessed height for each row. The virtualizer uses it to compute offsets and the total spacer height before anything is measured.measureElementis a ref callback. When a row renders, the virtualizer reads its real height, stores it, and recalculates the offsets of the rows below it.
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>
);
}Compare this with the fixed-height version. The row no longer sets height, so the content decides it. The data-index attribute tells the virtualizer which row a measured element belongs to. Without it, the measurement cannot be matched to an item. Position comes from transform: translateY(v.start), where v.start is the row's current offset, including any measurements already made.
Common errors
- Forgetting
data-index. The virtualizer cannot map the element to a row, and the heights are wrong or ignored. - Setting a fixed
heighton the row. The measurement then returns your fixed value instead of the content height. - Using margins between rows. Margins fall outside the element's measured box, so rows overlap. Use padding inside the row, or the virtualizer's
gapoption. - A poor estimate. If the estimate is far from reality, the scrollbar thumb jumps as rows are measured, and the total height changes while the user scrolls. Pick the average real height, not the smallest.
- Content that changes size after the first render. Examples are images that load late and text that reflows on resize. The measurement is observed with a resize observer, so this normally works, but give images a reserved size where you can to avoid layout shifts.
Trade-offs
Measured sizes cost extra layout reads, so dynamic lists do slightly more work per row than fixed lists. If your rows can have a known fixed height, use it. The cached measurements also depend on the row index. If you insert items at the top of the list, indexes shift and measurements can attach to the wrong rows unless you provide a stable getItemKey.
Exercise
A list uses estimateSize: () => 50, but real rows average 120px. The user drags the scrollbar thumb and the thumb jumps as new rows appear. Why does this happen, and what is the fix?
Show answer
The virtualizer computes the total height from the estimates, so the total is too small at first. Each time a row is measured, the total grows and the thumb position changes. Set the estimate close to the real average (about 120), and confirm each row element has a data-index and ref={virtualizer.measureElement} so measurements are recorded.