Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Pagination and Infinite Queries | Updating Data and Advanced Query Features
React Query Essentials

bookPagination and Infinite Queries

When working with large datasets in web applications, you often need to display data in manageable chunks, or "pages," rather than loading everything at once. This approach is called paginated data fetching. Pagination helps keep your app fast and responsive by requesting only a subset of data from the server at a time. React Query provides powerful tools for pagination and also supports infinite scrolling, allowing you to fetch more data as the user interacts with the page.

The most common hook for infinite scrolling in React Query is useInfiniteQuery. Unlike useQuery, which is designed for a single request, useInfiniteQuery manages a series of related requests, each fetching the next page of data. It keeps track of all loaded pages and provides methods to fetch additional pages when needed. This is especially useful for implementing features like "Load More" buttons or automatically loading more data as the user scrolls.

To implement infinite scrolling, you need to structure your data fetching so that each request knows which page to load next. React Query's useInfiniteQuery accepts a function that receives a pageParam argument, which you use to determine which page to fetch. The hook returns a fetchNextPage function that you can call whenever you want to load more data.

Here is a simplified example of how you might use useInfiniteQuery to load more items as the user scrolls:

import { useInfiniteQuery } from "@tanstack/react-query";

function fetchItems({ pageParam = 1 }) {
  return fetch(`/api/items?page=${pageParam}`).then((res) => res.json());
}

function ItemList() {
  const { data, fetchNextPage, hasNextPage, isFetchingNextPage } =
    useInfiniteQuery({
      queryKey: ["items"],
      queryFn: fetchItems,
      getNextPageParam: (lastPage, allPages) => {
        return lastPage.hasMore ? allPages.length + 1 : undefined;
      },
    });

  const items = data ? data.pages.flatMap((page) => page.items) : [];

  return (
    <div>
      <ul>
        {items.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>

      <button
        onClick={() => fetchNextPage()}
        disabled={!hasNextPage || isFetchingNextPage}
      >
        {isFetchingNextPage
          ? "Loading more..."
          : hasNextPage
          ? "Load More"
          : "No more items"}
      </button>
    </div>
  );
}

In this example, useInfiniteQuery manages multiple pages of data. The getNextPageParam function tells React Query how to determine the next page to fetch, based on the data from the last loaded page. The fetchNextPage function is called when the user clicks the "Load More" button, but you could also trigger it automatically as the user scrolls to the bottom of the list.

question mark

What is the main purpose of the useInfiniteQuery hook in React Query?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 3. ChapterΒ 3

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

bookPagination and Infinite Queries

Swipe to show menu

When working with large datasets in web applications, you often need to display data in manageable chunks, or "pages," rather than loading everything at once. This approach is called paginated data fetching. Pagination helps keep your app fast and responsive by requesting only a subset of data from the server at a time. React Query provides powerful tools for pagination and also supports infinite scrolling, allowing you to fetch more data as the user interacts with the page.

The most common hook for infinite scrolling in React Query is useInfiniteQuery. Unlike useQuery, which is designed for a single request, useInfiniteQuery manages a series of related requests, each fetching the next page of data. It keeps track of all loaded pages and provides methods to fetch additional pages when needed. This is especially useful for implementing features like "Load More" buttons or automatically loading more data as the user scrolls.

To implement infinite scrolling, you need to structure your data fetching so that each request knows which page to load next. React Query's useInfiniteQuery accepts a function that receives a pageParam argument, which you use to determine which page to fetch. The hook returns a fetchNextPage function that you can call whenever you want to load more data.

Here is a simplified example of how you might use useInfiniteQuery to load more items as the user scrolls:

import { useInfiniteQuery } from "@tanstack/react-query";

function fetchItems({ pageParam = 1 }) {
  return fetch(`/api/items?page=${pageParam}`).then((res) => res.json());
}

function ItemList() {
  const { data, fetchNextPage, hasNextPage, isFetchingNextPage } =
    useInfiniteQuery({
      queryKey: ["items"],
      queryFn: fetchItems,
      getNextPageParam: (lastPage, allPages) => {
        return lastPage.hasMore ? allPages.length + 1 : undefined;
      },
    });

  const items = data ? data.pages.flatMap((page) => page.items) : [];

  return (
    <div>
      <ul>
        {items.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>

      <button
        onClick={() => fetchNextPage()}
        disabled={!hasNextPage || isFetchingNextPage}
      >
        {isFetchingNextPage
          ? "Loading more..."
          : hasNextPage
          ? "Load More"
          : "No more items"}
      </button>
    </div>
  );
}

In this example, useInfiniteQuery manages multiple pages of data. The getNextPageParam function tells React Query how to determine the next page to fetch, based on the data from the last loaded page. The fetchNextPage function is called when the user clicks the "Load More" button, but you could also trigger it automatically as the user scrolls to the bottom of the list.

question mark

What is the main purpose of the useInfiniteQuery hook in React Query?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 3. ChapterΒ 3
some-alt