Course contentsShow
← React
Lesson 1281 of 2,39632. Lists and Keys Deep DiveFree lesson

Dynamic Item Heights

Handle items with unknown or variable heights using measureElement and dynamic size calculations.

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:

  1. Guesses initial heights using estimateSize (doesn't need to be perfect)
  2. Measures actual rendered elements via measureElement
  3. Adjusts scroll calculations as it learns real sizes
  4. 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.