Blog>
Snippets

Optimizing Overscan with TanStack Virtual

Present a code example on adjusting the overscan property in TanStack Virtual to optimize rendering performance without sacrificing user experience, including a brief explanation of what overscan is and when to modify it.
import { useVirtual } from '@tanstack/react-virtual';
Importing the useVirtual hook from TanStack Virtual library.
const rowVirtualizer = useVirtual({
  size: 1000, // Total number of items in the list
  parentRef, // Reference to the scrolling container
  overscan: 5 // Overscan count
});
Initializing the row virtualizer with a specified size of the list, a reference to the parent container, and an overscan count of 5. Overscan is the number of items rendered outside of the visible area to allow for smooth scrolling.
const handleScroll = (e) => {
  // Logic to increase or decrease overscan dynamically based on scroll speed could be implemented here.
};
An example function to handle scroll events where you could adjust the overscan dynamically based on the scroll velocity.