Blog>
Snippets

Handling Scroll Events Efficiently

Explains the setup for efficient handling of scroll events in TanStack Virtual Grid to enhance performance, especially with large datasets.
import { useRef } from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';
Imports necessary hooks from React and the useVirtualizer hook from @tanstack/react-virtual.
const parentRef = useRef(null);
Creates a ref for the parent container that will hold the virtualized list.
const rowVirtualizer = useVirtualizer({
    count: 1000, // Total number of items
    getScrollElement: () => parentRef.current,
    estimateSize: () => 35, // Estimated height for each item
    overscan: 5, // Number of items to prerender outside of the visible area
});
Initializes the virtualizer with an item count, a function to get the scrollable element, an estimated size for each item, and the number of items to overscan.
useEffect(() => {
    const handleScroll = (e) => {
        rowVirtualizer.scrollRangeToVisible(e.target.scrollTop, e.target.scrollTop + parentRef.current.clientHeight);
    };
    const scrollElement = parentRef.current;
    scrollElement.addEventListener('scroll', handleScroll);
    return () => scrollElement.removeEventListener('scroll', handleScroll);
}, [rowVirtualizer]);
Sets up a scroll event listener to the parent container. The event handler notifies the virtualizer of the visible scroll range, which helps in determining which items to render.