Blog>
Snippets

Installing TanStack Virtual and Setting Up a Basic Virtualized List

Demonstrate how to install TanStack Virtual library and set up a basic virtualized list in a React component.
// First, install the TanStack Virtual library by running:
// npm install @tanstack/react-virtual@beta
This command installs the TanStack Virtual library required for virtualizing lists in React applications.
import React, { useRef } from 'react';
import { useVirtual } from '@tanstack/react-virtual';

function VirtualList() {
  const parentRef = useRef(null);
  const rowVirtualizer = useVirtual({
    size: 1000, // Number of items
    parentRef,
    estimateSize: React.useCallback(() => 35, []), // Estimated size of each item
  });

  return (
    <div ref={parentRef} style={{height: '300px', overflow: 'auto'}}>
      <div style={{ height: rowVirtualizer.totalSize }}> // Set the height to the total size of the virtual items
        {rowVirtualizer.virtualItems.map(virtualItem => (
          <div
            key={virtualItem.index}
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              width: '100%',
              height: virtualItem.size,
              transform: `translateY(${virtualItem.start}px)` // Position item based on the virtualItem's calculated position
            }}
          >
            Item {virtualItem.index}
          </div>
        ))}
      </div>
    </div>
  );
}
This React component demonstrates the basic setup for a virtualized list using TanStack Virtual. It creates a list of 1000 items and uses the `useVirtual` hook to only render the items in the viewport, improving rendering performance for large lists.