Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 38 ยท Pagination and Infinite Queries

Infinite Queries with useInfiniteQuery

Learn useInfiniteQuery in TanStack Query v5: initialPageParam, getNextPageParam, fetchNextPage, hasNextPage, flattening pages and building a Load more button.

A paginated list replaces the page the user sees. An infinite list keeps adding to what is already there: "Load more" buttons, activity feeds, chat history, endless scrolling. You could build it with useState and an array that grows, but then you would have to rebuild caching, refetching and error handling yourself.

useInfiniteQuery does that for you. It stores all the pages as one cache entry and gives you functions to fetch the next page. This lesson covers the option names, the shape of data, and a working "Load more" list. Automatic scrolling and bidirectional lists follow in Infinite Scroll Patterns.

The three required pieces

JavaScript
const query = useInfiniteQuery({
  queryKey: ["feed"],
  queryFn: ({ pageParam }) => fetchFeed(pageParam),
  initialPageParam: 0,
  getNextPageParam: (lastPage, allPages, lastPageParam) => lastPage.nextCursor,
})
  1. queryFn receives pageParam. The library calls your function with the value that identifies the page to load (a cursor, page number or offset).
  2. initialPageParam is the pageParam for the very first page. In v5 it is required; in v4 you relied on undefined.
  3. getNextPageParam looks at the last page you fetched and returns the param for the next one, or undefined (or null) when there is nothing more. Whenever it returns undefined, hasNextPage becomes false.
flowchart LR
  A["initialPageParam = 0"] --> B["queryFn page 0"]
  B --> C["getNextPageParam(last) = 5"]
  C -->|fetchNextPage| D["queryFn page 5"]
  D --> E["getNextPageParam(last) = undefined"]
  E --> F["hasNextPage = false"]

Each page's result decides the param for the next request. Returning undefined ends the list.

The shape of data

With useQuery, data is whatever your function returned. With useInfiniteQuery, it is an object with two arrays:

JavaScript
{
  pages: [page0Result, page1Result, ...],
  pageParams: [0, 5, ...],
}

To render, flatten the pages: data.pages.flatMap((page) => page.items). The select option can do this once so components receive a flat list:

JavaScript
select: (data) => data.pages.flatMap((p) => p.items)

The state you get

Value Meaning
fetchNextPage() Load the next page using getNextPageParam
hasNextPage true while getNextPageParam returned a value
isFetchingNextPage A next-page request is running
isFetching Any request is running (including background refetches)
isPending The first page has not arrived yet

Use isFetchingNextPage, not isFetching, to label the Load more button, because isFetching is also true during a background refetch of all pages.

A Load more button

The fake API below returns five items at a time together with a nextCursor. The cursor is the index of the next item, or null at the end.

Load more with useInfiniteQuery

Press the button three times: 5, 10, then 13 items, and the button disables itself. The cursor chain 0 -> 5 -> 10 -> null is exactly what getNextPageParam produced.

Using the other getNextPageParam arguments

The function gets (lastPage, allPages, lastPageParam, allPageParams). That is enough for every pagination style:

JavaScript
// Page numbers: stop at the server's total
getNextPageParam: (lastPage, allPages, lastPageParam) =>
  lastPageParam < lastPage.totalPages ? lastPageParam + 1 : undefined,

// Offset style: stop when a short page arrives
getNextPageParam: (lastPage, allPages) =>
  lastPage.items.length === 20 ? allPages.length * 20 : undefined,

A short or empty last page is the usual "no more" signal when the server sends no cursor. Be careful with the empty-page rule: if the total is an exact multiple of the page size, you make one extra request that returns zero items. Prefer an explicit hasMore or nextCursor from the server when you can change it.

Refetching an infinite query

When an infinite query refetches (window focus, invalidateQueries), TanStack Query refetches every page loaded so far, one after another, from the first page, using each page's stored param. That keeps pages consistent (no duplicates or gaps when rows were inserted), but it has a cost: an infinite list with 30 pages makes 30 requests per refetch. Two tools help:

  • maxPages limits how many pages stay in the cache (older pages are dropped as new ones arrive).
  • staleTime stops needless refetches on focus.

Reading the pages in the cache

Because the data has a different shape, never mix an infinite query's key with a normal one. Use ["feed"] for the infinite list and a distinct key such as ["feed", "count"] for something else. Writing to it with setQueryData means preserving the { pages, pageParams } shape:

JavaScript
queryClient.setQueryData(["feed"], (old) => ({
  ...old,
  pages: old.pages.map((page) => ({
    ...page,
    items: page.items.filter((item) => item.id !== removedId),
  })),
}))

This is the shape you will use for optimistic updates on infinite lists later in this track.

Controlling the fetch with a stand-in

Real projects call fetch; the following sketch shows how the param flows, using the framework-agnostic @tanstack/query-core's InfiniteQueryObserver directly. No React is involved, so you can see the logic by itself.

JS Param chain without React

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The hook is a thin layer over this observer. Understanding the parameter chain makes the React code easy to debug: when a list stops loading, print what getNextPageParam returned.

Common mistakes

  • Forgetting initialPageParam. v5 throws a type error (and the first request gets undefined).
  • Returning null vs undefined. Both mean "no next page" in v5, but returning 0 or "" does not: they are values. Return undefined explicitly.
  • Using the same key for infinite and finite data. The cache would hold two different shapes under one key.
  • Duplicate items. If the server's order shifts while users page, items can appear twice. Cursors avoid most of this; otherwise de-duplicate by id in select.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does getNextPageParam return when there are no more pages?

    Returning undefined or null makes hasNextPage false. Other values, even 0 or an empty string, are treated as the next param.
  2. 2. What is the shape of data from useInfiniteQuery?

    All fetched pages are stored together with the params that fetched them, so you flatten data.pages to render.
  3. 3. Which flag should label a Load more button as busy?

    isFetchingNextPage is true only while a next-page request runs. isFetching also covers background refetches of existing pages.
  4. 4. What happens to a 10-page infinite query when it refetches?

    Refetching all pages keeps them consistent, but costs one request per page; maxPages and staleTime limit that.

Summary

  • useInfiniteQuery needs queryFn({ pageParam }), initialPageParam and getNextPageParam.
  • data is { pages, pageParams }; flatten pages to render.
  • fetchNextPage, hasNextPage and isFetchingNextPage drive Load more buttons.
  • A refetch re-requests every loaded page; use staleTime and maxPages to keep it cheap.
  • When editing the cache by hand, keep the { pages, pageParams } shape.

Next: Infinite Scroll Patterns