Sub topic 12
Paginated lists and keeping previous data
This chapter assumes you can write a basic useQuery call, that you know why query keys identify cache entries, and that you understand staleTime and gcTime. It builds a paginated list that doesn't flash a loading state between pages.
The problem with page-based keys
A paginated list shows one slice of a larger collection. The user clicks "Next", the page number changes, and the component needs different data.
The page number belongs in the query key. Each page then gets its own cache entry, and going back to a page you already visited can show cached data right away.
This creates a side effect. When page changes from 1 to 2, the query key changes, so the observer points at a cache entry that has no data yet. For a moment the query is in the pending state, and data is undefined. The list disappears, a spinner appears, and the list comes back. On every click, the layout jumps.
placeholderData fixes this. It lets the query show some other data while the real data for the new key loads.
Keeping the previous page visible
TanStack Query v5 ships a helper named keepPreviousData. You pass it as placeholderData. While the new page loads, data holds the previous page's result.
import { useState } from 'react'
import { keepPreviousData, useQuery } from '@tanstack/react-query'
type Project = { id: number; name: string }
type ProjectsPage = { items: Project[]; hasMore: boolean }
async function fetchProjectsPage(page: number): Promise<ProjectsPage> {
const res = await fetch(`/api/projects?page=${page}&limit=10`)
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}
export function PagedProjects() {
const [page, setPage] = useState(1)
const { data, isPending, isError, error, isFetching, isPlaceholderData } =
useQuery({
queryKey: ['projects', 'paged', { page }],
queryFn: () => fetchProjectsPage(page),
placeholderData: keepPreviousData,
})
if (isPending) return <p>Loading...</p>
if (isError) return <p>Something went wrong: {error.message}</p>
return (
<div>
<ul style={{ opacity: isPlaceholderData ? 0.5 : 1 }}>
{data.items.map((p) => (
<li key={p.id}>{p.name}</li>
))}
</ul>
<button
onClick={() => setPage((p) => Math.max(1, p - 1))}
disabled={page === 1}
>
Previous
</button>
<span> Page {page} </span>
<button
onClick={() => setPage((p) => p + 1)}
disabled={isPlaceholderData || !data.hasMore}
>
Next
</button>
{isFetching ? <span> Updating...</span> : null}
</div>
)
}Three details in this component matter.
isPendingis only true on the very first load. After that,dataalways exists, either real or placeholder, so the loading branch never runs again.isPlaceholderDatais true while the displayed data belongs to a different key than the one requested. The list dims during that time.isFetchingis true during any request, including background refetches. Use it for a subtle activity indicator.
What the status fields report
Placeholder data is not stored in the cache, and it doesn't change the query's status. The table shows what you see while moving from page 1 to a page 2 that is not cached.
| Moment | `status` | `fetchStatus` | `isPlaceholderData` | `data` |
|---|---|---|---|---|
| Page 1 loaded | `success` | `idle` | `false` | Page 1 |
| Clicked Next, page 2 loading | `success` | `fetching` | `true` | Page 1 (placeholder) |
| Page 2 arrived | `success` | `idle` | `false` | Page 2 |
The status is success while the placeholder is shown. A component that only checks status can't tell that it is showing the wrong page. That's why isPlaceholderData exists.
Disabling Next while the placeholder is shown
Look at the Next button in the example: disabled={isPlaceholderData || !data.hasMore}.
Without the isPlaceholderData check, hasMore would come from the previous page. A user who clicks Next twice quickly could jump past a page that hasn't loaded, or past the last page. Always derive "can go forward" from data that belongs to the current key.
Prefetching the next page
keepPreviousData hides the wait, but it doesn't remove it. If you can guess the next request, fetch it early with queryClient.prefetchQuery. This puts the result in the cache under the same key the real query will use.
import { useEffect, useState } from 'react'
import {
keepPreviousData,
useQuery,
useQueryClient,
} from '@tanstack/react-query'
type Project = { id: number; name: string }
type ProjectsPage = { items: Project[]; hasMore: boolean }
async function fetchProjectsPage(page: number): Promise<ProjectsPage> {
const res = await fetch(`/api/projects?page=${page}&limit=10`)
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}
const pageQuery = (page: number) => ({
queryKey: ['projects', 'paged', { page }],
queryFn: () => fetchProjectsPage(page),
staleTime: 30 * 1000,
})
export function PagedProjectsPrefetch() {
const queryClient = useQueryClient()
const [page, setPage] = useState(1)
const { data, isPlaceholderData } = useQuery({
...pageQuery(page),
placeholderData: keepPreviousData,
})
useEffect(() => {
if (!isPlaceholderData && data?.hasMore) {
queryClient.prefetchQuery(pageQuery(page + 1))
}
}, [data, isPlaceholderData, page, queryClient])
return (
<div>
<ul>
{data?.items.map((p) => (
<li key={p.id}>{p.name}</li>
))}
</ul>
<button onClick={() => setPage((p) => p + 1)} disabled={!data?.hasMore}>
Next
</button>
</div>
)
}Two points make this work.
- Both the real query and the prefetch use the shared
pageQueryfactory. The key andqueryFncan't drift apart, so the prefetched entry is exactly the one the next render looks up. prefetchQueryrespectsstaleTime. If the entry already exists and is fresh, it does nothing. Without astaleTime, the default of 0 treats cached data as stale, so the prefetch fetches again every time the effect runs.
The effect also waits for isPlaceholderData to be false. That keeps it from prefetching page 3 based on the metadata of page 1.
Edge cases and common errors
- Page out of range. If the user types
?page=99and the server returns an empty list or a 404, your component must handle it. A 404 is an error state. An emptyitemsarray is a success with nothing to show. Decide which one your API returns and render both cases. - Deleted items shift pages. With offset pagination (
page=2&limit=10), deleting an item on page 1 moves one item from page 2 onto page 1. Cached pages can then show duplicates or skip an item. Invalidating['projects', 'paged']after mutations refetches the visible page, and cached pages refetch when next used. Cursor-based APIs avoid this problem. - Shared keys between
useQueryanduseInfiniteQuery. An infinite query stores{ pages, pageParams }, while a paged query stores a single page. Use different keys, such as['projects', 'paged', ...]and['projects', 'infinite']. Sharing a key makes components read data of the wrong shape. - Putting the whole filter in the key. If the list also has a search term or a sort order, put those in the key object:
['projects', 'paged', { page, search, sort }]. A change in any of them creates a new entry, andkeepPreviousDatakeeps showing the old list while the new one loads. - Resetting to page 1. When a filter changes, set
pageback to 1 in the same event handler. Otherwise the query requests page 5 of the new filter, which may not exist. - Placeholder across unrelated lists.
keepPreviousDatais meant for the same list with different parameters. If the key switches to a completely different resource, the old data is misleading. Use it only where "previous result" is a sensible stand-in.
When to use this approach
Use page-based queries with keepPreviousData when users jump between numbered pages, the list has a clear total, or pages should be bookmarkable through the URL. Use useInfiniteQuery, covered in the next chapter, when the user scrolls forward through a feed and older pages should stay on screen.
Exercise
A paginated list uses placeholderData: keepPreviousData. The user is on page 3 and clicks Next. Before page 4 arrives, what are status, isPending, and isPlaceholderData, and why should the Next button be disabled at that moment?
Show answer
status is success and isPending is false, because placeholder data counts as data. isPlaceholderData is true because the displayed data is page 3, not the requested page 4. The Next button should be disabled because values such as hasMore come from page 3, so a second click could skip past page 4 or run past the last page.
Exercise
Why does the prefetch example set staleTime: 30 * 1000 in the shared pageQuery factory, and what would happen without it?
Show answer
prefetchQuery only skips the request when a cache entry exists and is still fresh. With the default staleTime of 0, any cached entry is already stale, so the prefetch would fetch the next page again every time the effect runs. The staleTime keeps the prefetched page fresh long enough for the user's click to use it without another request.