Blog>
Snippets

Installing and Initializing TanStack Virtual

Demonstrate how to install TanStack Virtual via npm and set up a basic virtualized list in a React component.
// Install TanStack Virtual via npm
npm install @tanstack/react-virtual
This command installs the TanStack Virtual library in your project, making its functionalities available for use.
import React from 'react';
import { useVirtual } from '@tanstack/react-virtual';

function VirtualList() {
  // Initialize virtualizer with item count and item size
  const rowVirtualizer = useVirtual({
    size: 1000, // Total number of items
    estimateSize: () => 35, // Estimated size of each item
    parentRef: React.useRef(), // Ref to the scrolling parent
  });

  return (
    <div
      ref={rowVirtualizer.parentRef}
      style={{ height: `300px`, overflow: 'auto' }}
    >
      <div
        style={{
          height: `${rowVirtualizer.totalSize}px`,
          width: '100%',
          position: 'relative',
        }}
      >
        {rowVirtualizer.virtualItems.map((virtualRow) => (
          <div
            key={virtualRow.index}
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              height: `${virtualRow.size}px`,
              transform: `translateY(${virtualRow.start}px)`,
              width: '100%',
            }}
          >
            Item {virtualRow.index}
          </div>
        ))}
      </div>
    </div>
  );
}
This code snippet defines a React component named VirtualList using the TanStack Virtual library. It demonstrates how to set up and use the useVirtual hook to create a basic virtualized list with 1000 items, each estimated to be 35px in height. The virtualized list optimizes rendering by only displaying the items currently within view, improving performance for large lists.