Blog>
Snippets

Implementing a Basic Virtual List with TanStack Virtual

Demonstrate how to create a basic virtual list in React using TanStack Virtual, covering the initialization of the virtualizer and rendering a set of items.
import React, { useRef } from 'react';
import { useVirtual } from '@tanstack/react-virtual';
Import necessary modules from React and TanStack Virtual.
const VirtualList = ({ items }) => {
  const parentRef = useRef(null);
  const rowVirtualizer = useVirtual({
    size: items.length, // the number of items
    parentRef, // element that hosts the scroll
    estimateSize: React.useCallback(() => 35, []), // estimated size of an item
    overscan: 5, // number of items to render outside of the view
  });

  return (
    <div ref={parentRef} style={{ height: '300px', overflow: 'auto' }}>
      <div style={{ height: rowVirtualizer.totalSize }}>
        {rowVirtualizer.virtualItems.map(virtualItem => (
          <div key={virtualItem.index} style={{
            position: 'absolute',
            top: 0,
            left: 0,
            width: '100%',
            transform: `translateY(${virtualItem.start}px)`
          }}>
            {items[virtualItem.index]}
          </div>
        ))}
      </div>
    </div>
  );
};
Defines a VirtualList component that takes an array of items as props. It uses the useVirtual hook to create a virtualizer based on the items' length, with a ref to the scrolling parent and an estimated item size. The component returns a scrollable div that contains another div, which adjusts its height based on totalSize calculated by the virtualizer. Only the items in the viewport (plus an overscan buffer) are rendered, and they're absolutely positioned within the parent based on their virtualItem.start position.
export default VirtualList;
Exports the VirtualList component for use in other parts of the application.