Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 38 ยท Pagination and Infinite Queries

Paginated Queries

Build page-by-page lists with TanStack Query: put the page number in the query key, keep the old page on screen with placeholderData, and prefetch the next page.

Most real lists are too long to load at once. Servers return them in pages, and the user moves between pages with Previous and Next buttons or numbered links. TanStack Query handles this with nothing special: a page is just another query, and the page number is part of its key.

The one thing you have to design is the transition. When the user clicks "Next", the new page has no cached data yet. Without care, the list disappears, a spinner shows, and the list comes back. This lesson shows how to make that transition smooth with placeholderData and how to hide the wait entirely by prefetching.

The examples load @tanstack/react-query v5 from a CDN and talk to a fake in-memory API that waits a few hundred milliseconds, so everything runs in your browser. A real app would call fetch instead of the fake function.

The page number belongs in the key

A query key identifies the data. Page 1 and page 2 are different data, so they need different keys:

JavaScript
useQuery({
  queryKey: ["posts", { page }],
  queryFn: () => fetchPosts(page),
})

Every page gets its own cache entry. Going back to a page you already visited shows it immediately from the cache (and refetches in the background if it is stale). You do not need to write any "remember the pages" code.

The queryFn closes over page, and the key contains page too. Keeping those two in sync is the most important rule of this chapter: if a value changes what the function returns, it must be in the key.

A first paginated list

Paginated list without any help

Click Next, then Previous. The first visit to each page shows "Loading page N..." because that key has no data (isPending is true). Going back is instant: the cache already has page 1. The flicker on first visits is what we want to remove.

Keep the previous page with placeholderData

TanStack Query v5 ships a ready-made helper, keepPreviousData. Pass it as placeholderData and the query shows the previous query's data while the new key is loading:

JavaScript
import { keepPreviousData, useQuery } from "@tanstack/react-query";

const { data, isPlaceholderData } = useQuery({
  queryKey: ["posts", { page }],
  queryFn: () => fetchPosts(page),
  placeholderData: keepPreviousData,
})

While the new page loads, status is already "success" (so isPending is false and data is defined), and isPlaceholderData is true. When the real data arrives, data is replaced and isPlaceholderData becomes false.

Use isPlaceholderData to guard against stale interactions. A classic bug is enabling "Next" based on the old page's hasMore flag while the new page is still loading, which lets the user race ahead. Disable the button while the data is a placeholder.

In v4 this feature was the option keepPreviousData: true. In v5 that option is gone. Use placeholderData: keepPreviousData instead. Old tutorials that show the boolean option are out of date.

keepPreviousData and isPlaceholderData

The old list stays visible but dimmed while the next page loads, and the Next button is disabled until the real data arrives. No layout jump, no spinner.

Prefetch the next page

Even better is for the user never to wait. After page N renders, start loading page N+1 in the background with queryClient.prefetchQuery. It uses the same key and function as the real query, so when the user clicks Next, the data is already cached:

JavaScript
const queryClient = useQueryClient();

useEffect(() => {
  if (!isPlaceholderData && data?.hasMore) {
    queryClient.prefetchQuery({
      queryKey: ["posts", { page: page + 1 }],
      queryFn: () => fetchPosts(page + 1),
    });
  }
}, [data, isPlaceholderData, page, queryClient]);

Keep the queryFn in one shared function (or use queryOptions, shown in the Suspense and Prefetching chapter) so the key and function cannot drift apart between the hook and the prefetch call.

Prefetching the next page

Wait a second after the page loads, then click Next. The list changes at once because page 2 was prefetched, and the counter shows that page 3 started loading in the background.

Pagination styles and their keys

Servers paginate in different ways. The key should contain whatever identifies the page:

Style Request Key example
Page number ?page=3&limit=20 ["posts", { page: 3 }]
Offset ?offset=40&limit=20 ["posts", { offset: 40 }]
Cursor ?after=abc123 ["posts", { cursor: "abc123" }]

Page numbers and offsets allow jumping to any page. Cursors are stable when rows are inserted while the user browses, but you can only move forward from the cursor you were given. For "load more" and endless feeds, cursors pair naturally with infinite queries, covered in Infinite Queries.

Add filters and sorting to the same key object, so changing a filter starts again from a fresh entry: ["posts", { page, sort, search }]. When a filter changes you normally reset page to 1 in the same event handler.

Common mistakes

  • Page not in the key. Every page then shares one cache entry, and the list never updates.
  • Using isLoading or isPending to gate the whole UI. With keepPreviousData the query is never pending after the first page, so also check isPlaceholderData.
  • Prefetching without a guard. Prefetch only when the next page exists, and not while the current data is a placeholder.
  • Unbounded cache. Each page stays in memory for gcTime (5 minutes by default). That is fine for pages; for very large results tune gcTime.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the page number go in the query key?

    The key identifies the data. Page 1 and page 2 are different, so they need different keys; otherwise they would overwrite one cache entry.
  2. 2. What does placeholderData: keepPreviousData do while the next page loads?

    The query reports status success with the old data until the new data arrives. isPlaceholderData tells you the data is not yet for the current key.
  3. 3. In TanStack Query v5, how do you keep the previous page visible?

    The boolean option was removed in v5. The keepPreviousData function is imported from the library and passed as placeholderData.
  4. 4. Why disable the Next button while isPlaceholderData is true?

    The data on screen is from the previous key, so values such as hasMore describe the wrong page.

Summary

  • A page is just a query; put the page number, offset or cursor in the key.
  • placeholderData: keepPreviousData keeps the old page on screen while the new one loads.
  • isPlaceholderData tells you the data belongs to the previous key; use it to dim the list and guard the Next button.
  • prefetchQuery for page N+1 makes navigation feel instant.
  • Keep filters and sort order in the same key and reset the page when they change.

Next: Infinite Queries