Blog>
Snippets

Initializing TanStack Virtual in a React Component

Showcases the basic setup of TanStack Virtual by creating a virtualized list component, initializing the useVirtual hook, and rendering a simple list.
import { useVirtual } from '@tanstack/react-virtual';
import React, { useRef, useState } from 'react';
Import necessary hooks from React and the useVirtual hook from @tanstack/react-virtual.
const VirtualizedList = () => {
  const parentRef = useRef(null);
  const rowVirtualizer = useVirtual({
    size: 200, // Number of items
    parentRef, // Ref to the scrolling container
    estimateSize: React.useCallback(() => 35, []), // Estimated size of each item
    overscan: 5, // How many items to render outside of the visible area
  });

  return (
    <div ref={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,
            width: '100%',
            transform: `translateY(${virtualRow.start}px)`
          }}>
            Item {virtualRow.index}
          </div>
        ))}
      </div>
    </div>
  );
};
Defines a VirtualizedList component that uses the useVirtual hook. It creates a ref for the scrollable parent element, initializes the virtualization with parameters like the total number of items and their estimated size, and then maps over the virtual items to render only those currently in the viewport. It demonstrates how to handle scrolling and virtualization with fixed item sizes.
export default VirtualizedList;
Exports the VirtualizedList component for use in other parts of the application.