Blog>
Snippets

Optimizing Overscan Counts to Reduce Render Load

Present a code example that explains how to optimize overscan counts in TanStack Virtual, effectively reducing the number of items rendered outside of the viewport.
import { useVirtual } from 'tanstack-virtual';

function VirtualList({ items }) {
  // Initialize the virtualizer with the total number of items
  const virtualRow = useVirtual({
    size: items.length,
    // Setting the overscan count to a modest value
    // Overscan refers to the number of items rendered outside of the current viewport
    // A balanced value ensures items are ready just before they enter the viewport
    // without rendering too many unnecessary items
    overscan: 5,
  });

  return (
    <div style={{ height: '500px', overflow: 'auto' }}>
      <div style={{ height: virtualRow.totalSize }}> // The container adapting its size
        {virtualRow.virtualItems.map(virtualItem => (
          // Each item positioned absolutely based on its start
          <div key={virtualItem.key} style={{ position: 'absolute', top: 0, left: virtualItem.start }}>
            {items[virtualItem.index]} // Rendering the actual item
          </div>
        ))}
      </div>
    </div>
  );
}
This code demonstrates how to use the TanStack Virtual library to create a virtualized list with optimized overscan. Overscan is set to 5, meaning that five items outside of the current viewport are pre-rendered to ensure a smooth scrolling experience without excessively loading off-screen items. The `virtualRow` object calculates the dynamic positioning and rendering of items based on the scroll position, optimizing performance by limiting unnecessary renders.