Blog>
Snippets

Implementing Dynamic Item Sizes with TanStack Virtual

Provide an example of configuring TanStack Virtual to handle list items with dynamic sizes, ensuring efficient rendering and scrolling.
import { useVirtual } from '@tanstack/react-virtual';
First, import the useVirtual hook from @tanstack/react-virtual.
const parentRef = useRef();
Create a ref for the parent container to measure its size.
const rowVirtualizer = useVirtual({
  size: items.length,
  parentRef,
  estimateSize: useCallback(() => 50, []),
  overscan: 5,
});
Initialize the row virtualizer with the total number of items, parent container ref, an estimation of item size (can be dynamic based on content), and overscan for better scroll behavior.
return (
  <div ref={parentRef} style={{ height: `300px`, overflow: 'auto' }}>
    <div style={{ height: `${rowVirtualizer.totalSize}px`, position: 'relative' }}>
      {rowVirtualizer.virtualItems.map(virtualRow => (
        <div
          key={virtualRow.index}
          ref={virtualRow.measureRef}
          style={{
            position: 'absolute',
            top: 0,
            left: 0,
            width: '100%',
            transform: `translateY(${virtualRow.start}px)`
          }}
        >
          {renderRow(items[virtualRow.index], virtualRow.index)}
        </div>
      ))}
    </div>
  </div>
);
Render the virtual list inside a container. Use totalSize for dynamic container height and map over virtualItems to render only visible items, positioning them with translateY. The measureRef is used to automatically update item sizes.