Blog>
Snippets

Integrating React-Query with Infinite Scroll

Illustrate how to use react-query's useInfiniteQuery hook for fetching data page by page and integrating it with TanStack Virtual for an infinite scrolling list.
import { useInfiniteQuery } from '@tanstack/react-query';
import { getItems } from './api'; // Your API function to fetch data
Import statements for using useInfiniteQuery from React Query and a sample API function for fetching items.
const fetchItems = ({ pageParam = 1 }) => getItems(pageParam);

const { data, fetchNextPage, hasNextPage } = useInfiniteQuery(
  ['items'], 
  fetchItems, 
  {
    getNextPageParam: (lastPage, pages) => lastPage.nextPage ?? undefined
  }
);
Define the fetchItems function, and destructure necessary methods and properties from useInfiniteQuery. It fetches the data page by page, determining the next page parameter dynamically.
import { Virtuoso } from 'react-virtuoso';

<Virtuoso
  data={data?.pages.flatMap((page) => page.items)}
  endReached={() => hasNextPage && fetchNextPage()}
  itemContent={(index, item) => (
    <div>{item.name}</div> // Customize this render function based on your data structure
  )}
/>
Integration of TanStack Virtual (Virtuoso) with the infinite query data. The Virtuoso component handles the virtual scrolling, rendering items as they become visible, and calling fetchNextPage when the end is reached.