Blog>
Snippets

Efficient Data Fetching for Infinite Scrolling

Explain how to implement an efficient data fetching strategy for a virtualized list with infinite scrolling, using TanStack Virtual to handle large data sets seamlessly.
import { useVirtualizer } from '@tanstack/react-virtual';
Imports the useVirtualizer hook from the TanStack Virtual library.
const fetchMoreItems = async (startIndex, limit) => {
  // Replace with your data fetching logic
  // This function should return the next set of items starting from `startIndex` with a maximum of `limit` items.
};
Defines an asynchronous function to fetch more items from the server or API, starting from a specific index.
const RowVirtualizer = useVirtualizer({
  count: 1000, // Total count of items (adjust based on actual data)
  getScrollElement: () => document.getElementById('scroll-container'),
  estimateSize: () => 35, // Adjust based on your row height
  overscan: 5, // Number of items to render outside of the visible area
  onRangeChange: ({ startIndex, endIndex }) => {
    // Implement logic to load more items based on startIndex and endIndex
    fetchMoreItems(startIndex, 100).then(newItems => {
      // Update your state or data source with the new items
    });
  }
});
Initializes the row virtualizer with specific configurations such as the total item count, a function to get the scrolling container, estimated size of an item, overscan amount, and a function to handle range changes for loading more items.
const items = RowVirtualizer.getVirtualItems();
items.forEach((virtualItem) => {
  const rowElement = document.createElement('div');
  // Set properties on rowElement based on virtualItem, like transforming it to align with the virtual scroll position
});
Retrieves the list of virtual items that should currently be rendered based on the scroll position and iterates over them to create and position row elements accordingly.