Sub topic 12
Paginated lists and keeping previous data
This chapter assumes you know useQuery, query keys, and staleTime from earlier chapters. It also assumes basic React state with useState.
Pagination as a query key problem
A paginated list is a normal query where the page number is part of the query key. Each page gets its own cache entry, so going back to a page you already visited can show cached data right away.
import { useState } from 'react'
import { 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}`)
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}
function PagedProjects() {
const [page, setPage] = useState(0)
const { data, isPending, isError, error } = useQuery({
queryKey: ['projects', 'paged', page],
queryFn: () => fetchProjectsPage(page),
})
if (isPending) return <p>Loading...</p>
if (isError) return <p>Something went wrong: {error.message}</p>
return (
<div>
<ul>
{data.items.map((p) => (
<li key={p.id}>{p.name}</li>
))}
</ul>
<button onClick={() => setPage((p) => p - 1)} disabled={page === 0}>
Previous
</button>
<button onClick={() => setPage((p) => p + 1)} disabled={!data.hasMore}>
Next
</button>
</div>
)
}The flicker problem
When page changes, the key changes to one with no cache entry. The query goes back to pending, data is undefined, and the list is replaced by "Loading..." on every click. The screen flickers and the scroll position can jump.
Keeping previous data with placeholderData
The placeholderData option supplies data to show while the real data loads. TanStack Query v5 exports keepPreviousData, a ready-made function that returns the data from the previous query.
import { useQuery, keepPreviousData } from '@tanstack/react-query'
const { data, isPlaceholderData } = useQuery({
queryKey: ['projects', 'paged', page],
queryFn: () => fetchProjectsPage(page),
placeholderData: keepPreviousData,
})Now the query is in success status while the new page loads, and data holds the old page. The flag isPlaceholderData is true during that time. Placeholder data is never written to the cache.
Use the flag to avoid a bad "Next" click. The hasMore value belongs to the old page until the new one arrives:
<button
onClick={() => setPage((p) => p + 1)}
disabled={isPlaceholderData || !data?.hasMore}
>
Next
</button>You can also dim the list while isPlaceholderData is true, so users see that a fetch is in progress.
Common errors
- Leaving the page out of the query key. Every page then shares one cache entry and the list never changes.
- Using
keepPreviousDataas an option name. In v5 it is a function you pass toplaceholderData. - Trusting
hasMorewhileisPlaceholderDatais true. It describes the previous page. - Forgetting
staleTime. Without it, a revisited page shows cached data but refetches in the background.
Exercise
A user clicks "Next" and the list stays on the old page for a moment before updating. Which query field tells you the old page is still on screen, and how should it affect the "Next" button?
Show answer
isPlaceholderData is true while the old page is shown as placeholder data. Disable "Next" while it is true, because hasMore and the items still describe the previous page, and a second click would skip a page.