Blog>
Snippets

Basic Setup of TanStack Virtual with a React Component

Show how to set up TanStack Virtual in a React project by creating a basic virtualized list component.
import { useVirtualizer } from '@tanstack/react-virtual';
Importing the useVirtualizer hook from TanStack's react-virtual library.
import React, { useRef } from 'react';
Importing React and useRef hook for accessing DOM elements.
const VirtualizedList = ({ items }) => {
  const parentRef = useRef();
  const rowVirtualizer = useVirtualizer({
    count: items.length,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 35,
    overscan: 5
  });

  return (
    <div ref={parentRef} style={{ height: `300px`, overflow: 'auto' }}>
      <div style={{ height: `${rowVirtualizer.getTotalSize()}px`, width: '100%', position: 'relative' }}>
        {rowVirtualizer.getVirtualItems().map(virtualRow => (
          <div key={virtualRow.key} style={{ position: 'absolute', top: 0, left: 0, width: '100%', transform: `translateY(${virtualRow.start}px)` }}>
            {items[virtualRow.index]}
          </div>
        ))}
      </div>
    </div>
  );
};
Defining a React component for displaying a virtualized list. It uses the useVirtualizer hook to create a virtual list that only renders items in the viewport, improving performance for large lists.
export default VirtualizedList;
Exporting the VirtualizedList component so it can be used in other parts of the application.