Blog>
Snippets

Setting Up TanStack Virtual v3 in a React Project

Demonstrate how to install TanStack Virtual v3 and set it up within a React application, leading to the creation of a basic virtualized list.
npm install @tanstack/react-virtual
Install TanStack Virtual v3 via npm to include it in your project.
import React from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';
Import React and the useVirtualizer hook from @tanstack/react-virtual in your component file.
function VirtualList() {
  const parentRef = React.useRef(null);
  const rowVirtualizer = useVirtualizer({
    count: 10000,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 35,
    overscan: 5,
  });

  return (
    <div ref={parentRef} style={{ height: '500px', overflow: 'auto' }}>
      {rowVirtualizer.getVirtualItems().map(virtualRow => (
        <div key={virtualRow.key} style={{
          position: 'absolute',
          top: 0,
          left: 0,
          width: '100%',
          transform: `translateY(${virtualRow.start}px)`
        }}>
          Row {virtualRow.index}
        </div>
      ))}
    </div>
  );
}
Define a VirtualList component. Initialize the row virtualizer within the component using useVirtualizer hook, providing configuration for virtualization, such as the total count of items and the estimate size of each item. Render a div as a scrollable container for the list, and map over rowVirtualizer.getVirtualItems() to render each virtual row. Each row is absolutely positioned within the container based on its virtual position.