Blog>
Snippets

Basic Setup of TanStack Virtual in React

Demonstrate how to install TanStack Virtual and create a basic virtualized list component in a React application.
// Step 1: Install TanStack Virtual via npm or yarn
// npm install @tanstack/react-virtual
// yarn add @tanstack/react-virtual
This step installs the TanStack Virtual package, which is necessary for creating a virtualized list in React.
import React, { useRef } from 'react';
import { useVirtual } from '@tanstack/react-virtual';
Import necessary hooks from React and TanStack Virtual. useRef is used to reference the scrolling container, and useVirtual is the core hook of TanStack Virtual for implementing virtualization.
function VirtualList() {
  // Ref for the parent container
  const parentRef = useRef();
  // Create items array
  const items = Array.from({ length: 1000 }, (_, i) => `Item ${i}`);
  // Initialize the virtualizer
  const rowVirtualizer = useVirtual({
    size: items.length, // Number of items
    parentRef, // Reference to the scrolling container
  });

  return (
    <div
      ref={parentRef}
      style={{
        height: `150px`,
        width: `300px`,
        overflow: 'auto'
      }}
    >
      <div
        style={{
          height: `${rowVirtualizer.totalSize}px`,
          width: '100%',
          position: 'relative'
        }}
      >
        {rowVirtualizer.virtualItems.map(virtualItem => (
          <div
            key={virtualItem.index}
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              width: '100%',
              height: `${virtualItem.size}px`,
              transform: `translateY(${virtualItem.start}px)`
            }}
          >
            {items[virtualItem.index]}
          </div>
        ))}
      </div>
    </div>
  );
}
Defines the VirtualList component. It uses useVirtual to create a virtualizer instance with information about the items and parent container. Items are rendered based on their virtual position for efficient, high-performance lists.