Blog>
Snippets

Optimizing Performance with Row Virtualization

Explain how to implement row virtualization in TanStack Table to improve performance when rendering large amounts of data.
import { useVirtual } from 'react-virtual';
First, import the useVirtual hook from react-virtual, which is needed for implementing row virtualization.
const parentRef = useRef();
Set up a ref for the parent container of the virtualized rows. This ref is used to track the scroll container.
const rowVirtualizer = useVirtual({
  size: items.length, // Total number of items
  parentRef, // Ref to the scrolling container
  estimateSize: useCallback(() => estimatedRowSize, [estimatedRowSize]) // Estimated row height
});
Initialize the row virtualizer from useVirtual, passing the total number of items, parent container ref, and estimated row size. The estimateSize function returns the estimated height for a row which helps in optimizing the scroll behavior.
return (
  <div ref={parentRef} style={{ overflow: 'auto' }}>
    <div style={{ height: `${rowVirtualizer.totalSize}px`, width: '100%', 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)`
          }}>
          {items[virtualRow.index]}
        </div>
      ))}
    </div>
  </div>
);
This code renders the virtualized rows. It sets up a container with a dynamic height based on the total size calculated by the row virtualizer. Inside, each virtual row is rendered absolutely positioned at its calculated vertical start position. The measureRef is used by react-virtual to measure the rendered items dynamically, aiding in accurate positioning and optimizing scroll performance.