Sub topic 9
Variable and Dynamically Measured Row Heights
This chapter assumes you have built the fixed-height list from the earlier chapters. You should be comfortable with the scroll container, the spacer element, and the visible-range calculation. You should also know the basics of useRef and useEffect, and how @tanstack/react-virtual replaces the hand-written scroll logic.
Why fixed-height math stops working
The hand-written list found the first visible row with one division: Math.floor(scrollTop / rowHeight). It placed row i at i * rowHeight. Both formulas assume every row has the same height.
Real lists break that assumption. Chat messages wrap to different line counts. Cards contain images that load late. Comments expand and collapse. The browser knows a row's height only after it renders the row, but virtualization exists so that most rows are never rendered. This is the core problem:
- To position row 500, you need the heights of rows 0 to 499.
- To know those heights, you would have to render them.
- Rendering them defeats the purpose of virtualizing.
The standard solution is to estimate first and measure later. Every row starts with a guessed height. When a row renders, you measure its real height and replace the guess. The total list height and the row offsets are recomputed from a mix of measured and estimated sizes.
The estimate-then-measure model
TanStack Virtual keeps a cache of sizes, one entry per row, keyed by the row's key. The cycle works like this:
- For rows with no measurement, the virtualizer calls
estimateSize(index). - It computes each row's
startoffset by adding the sizes of all rows above it. - It renders the rows in the visible range, plus overscan.
- Each rendered row reports its real height through
measureElement. - The cache is updated, offsets and total size are recomputed, and React re-renders with corrected positions.
The user never sees these steps as separate frames. The correction normally happens before the next paint. A good estimate keeps the corrections small.
The dynamic list, line by line
Here is the dynamic list from the spine, with the parts that matter for measuring.
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>
);
}Three details make measurement work:
ref={virtualizer.measureElement}registers the row's DOM node with aResizeObserver. The observer fires when the row first renders and again whenever its size changes.data-index={v.index}tells the virtualizer which row the node belongs to. Without it, the virtualizer cannot match a measurement to a cache entry. In development it logs a warning about a missingdata-index.- No
heightin the row's style. The first fixed-height example setheight: v.size. Here the row is left at its natural height. If you set a height fromv.size, the browser reports exactly that height back and nothing is ever learned.
Positioning uses transform: translateY(...) instead of top. Changing a transform does not force layout the way changing top can, so offset corrections are cheap. Both approaches work.
Writing a better estimate
estimateSize receives the row index, so it can return different guesses for different rows. The closer the guess, the fewer visible corrections. Use whatever you know about the data:
import { useRef } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
type Message = { id: string; text: string; hasImage: boolean };
export function MessageList({ messages }: { messages: Message[] }) {
const parentRef = useRef<HTMLDivElement>(null);
const virtualizer = useVirtualizer({
count: messages.length,
getScrollElement: () => parentRef.current,
estimateSize: (index) => {
const m = messages[index];
const textLines = Math.ceil(m.text.length / 60);
return textLines * 20 + (m.hasImage ? 200 : 0) + 16;
},
getItemKey: (index) => messages[index].id,
gap: 8,
overscan: 5,
});
return (
<div ref={parentRef} style={{ height: 500, 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%",
padding: 8,
transform: `translateY(${v.start}px)`,
}}
>
{messages[v.index].text}
</div>
))}
</div>
</div>
);
}This example introduces two options:
getItemKeycontrols the cache key. The default key is the row index. If rows can be inserted, removed, or reordered, an index key attaches a measurement to the wrong row. Keying by a stable id keeps each measurement with its own data.gapadds space between rows. Use it or padding instead of CSS margins. The measurement reads the element's own box, so a margin on the row is not counted and rows will overlap or leave uneven spacing.
What gets measured, and when it changes
The ResizeObserver reports a change whenever the row's box changes size. That covers most real cases without extra code:
| Cause of a height change | Handled automatically? |
|---|---|
| Image finishes loading and the row grows | Yes, if the image is inside the measured element |
| Text wraps differently after the container is resized | Yes |
| User expands a collapsible section in the row | Yes |
| Rows are measured, then the whole dataset is swapped | Only if keys change. Otherwise stale sizes remain |
| Font loads late and changes line heights | Usually yes, because the box size changes |
If you replace the data in a way that keeps the same keys but changes row content in ways the observer cannot see, call virtualizer.measure(). It clears the size cache so rows are re-measured from the estimates.
Common errors
Rows overlap or leave gaps. Check that the row has no fixed height, that data-index is present, and that ref={virtualizer.measureElement} is on the same element that receives the translateY. Measuring an inner child while positioning an outer wrapper gives wrong sizes.
The scrollbar thumb jumps or the total height keeps changing. This is expected while the cache fills in. The total is the sum of measured and estimated sizes. A poor estimate makes the total shift as the user scrolls. Improve estimateSize rather than hiding the effect.
Content shifts under the user's eyes when scrolling up. Scrolling up reveals rows above the viewport that were never measured. When their real size differs from the estimate, everything below moves. TanStack Virtual adjusts scrollTop when a row above the current scroll position changes size, which hides most of the shift. Large estimation errors can still cause visible movement. Reserve space for images, using an aspect-ratio or explicit width and height attributes, so the row height is known before the image loads.
Sizes seem wrong after inserting rows. This is almost always the default index key. Add getItemKey with a stable id.
Very expensive rows measure slowly. Measuring happens after render, so a row that is heavy to render is heavy to measure. Keep rows light, and memoize their content as covered in the keys and state chapter.
Trade-offs
Dynamic measurement is more flexible than fixed heights, but it costs something:
- Positions are approximate until rows have been seen. Jumping to a far-away index lands on an estimated offset and may correct itself after rows render.
- Each rendered row adds a
ResizeObserverentry. The cost is small for a few dozen rows, and the virtualizer removes entries as rows leave the window. - Fixed heights remain faster and more predictable. If you can constrain rows to a known height, for example by truncating text to one line, prefer that.
A middle option exists when sizes are known from data but not equal. If you can compute each height ahead of time, return it from estimateSize(index) and skip measureElement. The list then behaves like a fixed-height one, with no corrections.
Exercise
A virtualized list uses estimateSize: () => 60 and ref={virtualizer.measureElement}, but rows render stacked on top of each other and never resize to fit their content. The row's style includes height: v.size. Name two changes that fix the problem and explain the cause.
Show answer
Remove height: v.size from the row's style, and add data-index={v.index} to the same element that has the ref (if it is missing). Setting the height from v.size forces every row to the estimated 60px, so the observer measures 60px and never learns the real height. Without data-index, the virtualizer cannot match a measurement to a row in its cache. The ref must also sit on the element that receives the translateY, so the measured box is the positioned box.
Exercise
Your chat list lets users delete messages from the middle. After a deletion, several rows show the wrong spacing until they scroll. You are using the default item keys. What do you change, and why?
Show answer
Pass getItemKey: (index) => messages[index].id. By default the cache is keyed by index, so after a deletion every row below the removed one inherits the measured size of the row that used to hold that index. A stable id key keeps each measurement attached to its own message.