Blog>
Snippets

Virtualization with Large Datasets

Provide an example of how to implement virtualization in TanStack Table to improve performance with large datasets.
import { useVirtual } from 'react-virtual';
Importing the useVirtual hook from react-virtual package for virtualization.
const rowVirtualizer = useVirtual({
  size: data.length, // Total number of items
  parentRef, // Ref to the scrolling container
  estimateSize: useCallback(() => estimatedRowSize, [estimatedRowSize]), // Estimated size of each item
  overscan: 5, // How many items to render outside of the visible area
});
Setting up the row virtualizer with the `useVirtual` hook. The `size` is the total number of items in your dataset. `parentRef` is a ref to the scrolling container which needs to be provided. `estimateSize` is a function returning the estimated size for each item to help the virtualizer determine how many items to render initially and during scroll. `overscan` defines the number of items to render outside of the visible viewport, for smoother scrolling experience.
const parentRef = React.useRef();
Creating a ref for the parent element to pass to the useVirtual hook for tracking scrolling.
<div ref={parentRef} style={{ overflow: 'auto', height: `500px` }}>
  <div style={{ height: `${rowVirtualizer.totalSize}px`, position: 'relative' }}>
    {rowVirtualizer.virtualItems.map(virtualRow => (
      <div key={virtualRow.index} style={{ position: 'absolute', top: 0, left: 0, width: '100%', transform: `translateY(${virtualRow.start}px)` }}>
        {data[virtualRow.index].content}
      </div>
    ))}
  </div>
</div>
Rendering the virtualized list. The outer `div` is the scroll container with a reference to `parentRef`. The inner `div` sets its height to `rowVirtualizer.totalSize` to take up the correct amount of space in the viewport, simulating a full-length list without rendering all items. Each item is absolutely positioned within this container at its `virtualRow.start` position, effectively only rendering items in the viewport plus any overscan items.