Blog>
Snippets

Basic Infinite Scroll Implementation

Demonstrate a basic setup of infinite scroll using TanStack Virtual with a list of items, including setting up the virtualizer and rendering items on the screen as they become visible.
import { useRef } from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';
Imports the necessary hooks from React and the useVirtualizer function from TanStack Virtual.
const parentRef = useRef();
Creates a ref for the scrolling container.
const fetchData = async () => {/* Function to fetch your data */};
Defines a placeholder function to fetch more data. Replace this with your actual data fetching logic.
const { virtualItems, scrollToIndex } = useVirtualizer({
  count: infiniteData.length,
  getScrollElement: () => parentRef.current,
  estimateSize: () => 35,
  overscan: 10,
  onScroll: ({ scrollOffset, scrollDirection }) => {
    if (scrollOffset + windowHeight > totalScrollHeight - threshold) {
      fetchData();
    }
  }
});
Sets up the virtualizer with a count of items, a function to get the scrolling element, an estimate size for each item, an overscan amount for pre-loading items, and an onScroll function to fetch more data as the user scrolls near the bottom.
return (
  <div ref={parentRef} style={{ height: '100vh', overflow: 'auto' }}>
    {virtualItems.map(virtualItem => (
      <div
        key={virtualItem.index}
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          width: '100%',
          transform: `translateY(${virtualItem.start}px)`,
          height: `${virtualItem.size}px`
        }}
      >
        {`Item ${virtualItem.index}`}
      </div>
    ))}
  </div>
);
Renders the virtual items using the properties provided by the virtualizer, positioning each item according to its calculated start position.