useVirtualizer Hook Basics
You'll learn how to set up TanStack Virtual's useVirtualizer hook to virtualize a long list by configuring the three essential options.
The Core Setup
Think of useVirtualizer as a GPS system for your scrollable list. Instead of rendering every item in a 10,000-item array, the hook calculates which items are currently visible in the viewport and only renders those. To do this, it needs three pieces of information:
- A parent ref – The scrollable container's DOM element
- Item count – How many total items exist
- estimateSize – A function that returns each item's approximate height
How It Works
import { useVirtualizer } from '@tanstack/react-virtual';
import { useRef } from 'react';
function VirtualList({ items }) {
const parentRef = useRef(null);
const virtualizer = useVirtualizer({
count: items.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 35, // Each item is approximately 35px tall
});
return (
<div ref={parentRef} style={{ height: '400px', overflow: 'auto' }}>
<div style={{ height: `${virtualizer.getTotalSize()}px` }}>
{virtualizer.getVirtualItems().map(virtualItem => (
<div key={virtualItem.key}>
{items[virtualItem.index]}
</div>
))}
</div>
</div>
);
}
The estimateSize function tells the virtualizer how tall each item is. This doesn't need to be pixel-perfect—TanStack Virtual measures actual sizes and adjusts dynamically. The parent ref connects the hook to your scrollable container, letting it track scroll position and calculate visibility.
Key Takeaway: useVirtualizer requires three essentials: a ref to the scroll container, the total item count, and an estimateSize function that approximates item height—this enables rendering only visible items in long lists.