Sub topic 13
Infinite scrolling with useInfiniteQuery
This chapter assumes you can write a basic useQuery, you understand query keys and staleTime, and you have seen the paginated-list chapter. Infinite queries build on both.
How it differs from a paginated query
A paginated list shows one page at a time. Each page is a separate cache entry, keyed by the page number. An infinite list keeps all loaded pages together under one query key. useInfiniteQuery stores them as a single object with two arrays: pages (the data from each request) and pageParams (the value used to fetch each page).
Use it for "Load more" buttons, feeds, and scroll-triggered lists.
A working example
import { useInfiniteQuery } from '@tanstack/react-query'
type Project = { id: number; name: string }
type ProjectsPage = { items: Project[]; nextCursor: number | null }
async function fetchProjects(cursor: number): Promise<ProjectsPage> {
const res = await fetch(`/api/projects?cursor=${cursor}`)
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}
function Projects() {
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } =
useInfiniteQuery({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
})
return (
<div>
<ul>
{data?.pages.flatMap((page) =>
page.items.map((p) => <li key={p.id}>{p.name}</li>),
)}
</ul>
<button
disabled={!hasNextPage || isFetchingNextPage}
onClick={() => fetchNextPage()}
>
Load more
</button>
</div>
)
}Three options differ from useQuery:
initialPageParamis required. It is thepageParamfor the first request.queryFnreceivespageParamin its context object. Pass it to your fetch function.getNextPageParamreceives the last page and returns the param for the next request. Returningundefined(ornull) means there are no more pages, sohasNextPagebecomesfalse.
The request cycle
State flags to know
isFetchingNextPageistrueonly while a next page loads. Use it to disable the button or show a spinner at the bottom of the list.isFetchingis alsotrueduring background refetches, so it is not a reliable "loading more" signal.isPendingapplies only to the very first load.
Common errors
- Forgetting
undefinedat the end. IfgetNextPageParamalways returns a value,hasNextPagestaystrueand the last page is requested repeatedly. - Rendering
datadirectly.datais{ pages, pageParams }, not an array. Flatten withflatMap. - Using the same key as a paginated query. The cached shape differs, so give infinite queries their own key.
Exercise
Your API returns { items, hasMore } and pages are numbered from 1. Write initialPageParam and getNextPageParam for it, assuming you have the last page and allPages.
Show answer
Use initialPageParam: 1 and getNextPageParam: (lastPage, allPages) => lastPage.hasMore ? allPages.length + 1 : undefined. Returning undefined when hasMore is false makes hasNextPage false.
Exercise
A user scrolls through five pages, then returns to the tab and the query is stale. What does the refetch do, and how can you limit the cost?
Show answer
It refetches all five pages in order, starting with the first, so that the pages stay consistent with each other. To limit the cost, set maxPages, increase staleTime, or turn off refetchOnWindowFocus.