Dynamic Item Heights
What you'll learn: How to virtualize lists when each item's height is unknown or varies, using dynamic measurement and size calculations.
The Challenge with Variable Heights
So far, you've likely worked with virtualized lists where every item has the same height — easy to calculate! But real-world data doesn't always cooperate. Comments vary by content length, product cards have different image sizes, and expandable sections change on user interaction.
When heights are dynamic, you can't pre-calculate scroll positions. The virtualizer needs to measure each item after rendering and update its calculations.
How Dynamic Sizing Works
TanStack Virtual handles this through an estimateSize function and automatic measurement:
import { useVirtualizer } from '@tanstack/react-virtual';
const virtualizer = useVirtualizer({
count: items.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 100, // Initial guess
// Enables dynamic measurement
measureElement: (el) => el.getBoundingClientRect().height,
});
The virtualizer:
- Guesses initial heights using
estimateSize(doesn't need to be perfect) - Measures actual rendered elements via
measureElement - Adjusts scroll calculations as it learns real sizes
- Re-measures when content changes
Think of it like planning a road trip without knowing exact distances — you estimate, then correct your ETA as you actually drive each segment.
Setting the data-index Attribute
For measurement to work, attach data-index to each virtual item:
{virtualizer.getVirtualItems().map((virtualItem) => (
<div
key={virtualItem.key}
data-index={virtualItem.index}
ref={(node) => virtualizer.measureElement(node)}
>
{/* Variable height content */}
</div>
))}
This connects the DOM element to the virtual item so measurements update the right entry.
Key Takeaway: Dynamic item heights require estimateSize for initial guesses and measureElement with data-index to measure and adjust real heights after rendering, keeping virtualization accurate for variable-sized content.