Variable-Size Lists and Dynamic Heights
What you'll learn: How to virtualize lists where each item has a different height using VariableSizeList and estimatedItemSize.
The Challenge of Different Heights
Fixed-size virtualization works beautifully when every item is the same height—the library can calculate positions mathematically. But real-world lists often contain items with varying heights: chat messages, social media posts, product cards with different image sizes. For these, you need VariableSizeList from react-window.
How Variable-Size Lists Work
Instead of providing a single itemSize prop, you pass an itemSize function that returns the height for each specific index:
import { VariableSizeList } from 'react-window';
const MyVariableList = ({ items }) => {
const getItemSize = (index) => {
// Return the actual height for this specific item
return items[index].height; // e.g., 50, 120, 80, etc.
};
return (
<VariableSizeList
height={600}
itemCount={items.length}
itemSize={getItemSize}
width="100%"
>
{({ index, style }) => (
<div style={style}>{items[index].content}</div>
)}
</VariableSizeList>
);
};
The estimatedItemSize Optimization
When react-window doesn't know item heights upfront, it must measure them. The estimatedItemSize prop helps it make better guesses for unmeasured items:
<VariableSizeList
estimatedItemSize={75} // average expected height
itemSize={getItemSize}
// ... other props
>
Think of estimatedItemSize as telling the library: "Most items are around this tall." This improves scrollbar accuracy and positioning before items are actually measured.
When Heights Are Unknown
If you don't know heights until render, you'll need to measure items after mounting and call listRef.current.resetAfterIndex(index) to recalculate positions—but that's an advanced pattern requiring careful implementation.
Key Takeaway: Use VariableSizeList with an itemSize function when list items have different heights, and provide estimatedItemSize to improve initial scrolling estimates before actual measurements occur.