Sub topic 13
Infinite scrolling with useInfiniteQuery
This chapter assumes you know useQuery, query keys, and the cache (staleTime, gcTime) from earlier chapters. It also assumes you have read the pagination chapter, where each page was its own cache entry. Infinite queries take the opposite approach: one cache entry holds every page loaded so far.
When to use an infinite query
Use useInfiniteQuery when the user keeps adding to a list: "Load more" buttons, feeds, and scroll-triggered loading. Use ordinary pagination with placeholderData when the user jumps between discrete pages.
| Need | Better fit |
|---|---|
| Page 1, 2, 3 with numbered links | `useQuery` with the page number in the key |
| Append more items to what is already visible | `useInfiniteQuery` |
| Jump straight to page 40 | `useQuery` with the page number in the key |
| Feed that grows over time | `useInfiniteQuery` |
The shape of the data
A normal query stores one value. An infinite query stores an object with two arrays:
pages: one entry per fetched page, in order. Each entry is whatever yourqueryFnreturned.pageParams: the parameter used to fetch each page, in the same order.
Everything lives under a single query key. Loading page 3 appends to data.pages and does not create a new cache entry.
A complete example
This is the core pattern. Three options are specific to infinite queries.
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>
)
}The three options work like this:
queryFnreceives a context object withpageParam. For the first request,pageParamequalsinitialPageParam.initialPageParamis required in v5. TypeScript infers the type ofpageParamfrom it.getNextPageParamreceives the last page and returns the parameter for the next request. Returningundefinedornullmeans there are no more pages, andhasNextPagebecomesfalse.
The server contract here is cursor-based: each response says where the next page starts. That is the most reliable design, because the cursor does not shift when items are inserted or deleted.
Status flags to watch
Infinite queries add flags to the ones you already know.
isFetchingNextPageistrueonly while a "next page" request runs. Use it to disable the button or show a small spinner at the bottom of the list.isFetchingistruefor any fetch, including background refetches of existing pages. Do not use it to decide whether the initial skeleton is shown.isPendingistrueonly until the first page arrives. Use it for the full-screen loading state.hasNextPageisfalsewhengetNextPageParamreturnedundefinedornull. It is alsofalsebefore the first page has loaded.
Keep the "Load more" button visible but disabled while loading. This avoids layout shifts and double clicks.
Triggering fetches on scroll
Most feeds load automatically when the user nears the bottom. Place an empty element after the list, watch it with an IntersectionObserver, and call fetchNextPage when it becomes visible.
import { useEffect, useRef } from 'react'
type Props = {
onVisible: () => void
enabled: boolean
}
export function Sentinel({ onVisible, enabled }: Props) {
const ref = useRef<HTMLDivElement | null>(null)
useEffect(() => {
const node = ref.current
if (!node || !enabled) return
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) onVisible()
})
observer.observe(node)
return () => observer.disconnect()
}, [enabled, onVisible])
return <div ref={ref} style={{ height: 1 }} />
}Render it below the list like this:
<Sentinel
enabled={hasNextPage && !isFetchingNextPage}
onVisible={() => fetchNextPage()}
/>The enabled prop guards two failure cases. It stops requests when the list has ended, and it prevents a second request while one is in flight.
Refetching, invalidation, and the cost of many pages
An infinite query is one cache entry, so it follows the normal staleness rules. The effects are bigger, though. When the query refetches, whether from window focus, a reconnect, or invalidateQueries, TanStack Query refetches every loaded page, one after another, starting from the first. It fetches sequentially because each page's parameter comes from the previous page's response.
With 15 pages loaded, one invalidation means 15 requests. There are two ways to limit this.
- Set
staleTimeso that focus and mount refetches are rare. - Set
maxPagesto cap how many pages stay in the cache. When the limit is exceeded, the oldest page is dropped as a new one is added.
useInfiniteQuery({
queryKey: ['projects'],
queryFn: ({ pageParam }) => fetchProjects(pageParam),
initialPageParam: 0,
getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
staleTime: 60 * 1000,
maxPages: 5,
})maxPages is only safe if the server can return pages in both directions. If you drop page 1 and the user scrolls back up, the library needs to fetch it again. For that, supply getPreviousPageParam and call fetchPreviousPage. Without getPreviousPageParam, hasPreviousPage stays false.
Common mistakes
- Reusing a query key. An infinite query's data is
{ pages, pageParams }. A regularuseQuerywith the same key expects a different shape, and the two will corrupt each other. Give infinite lists their own key, such as['projects', 'infinite']. - Forgetting parameters in the key. If the list is filtered, put the filter in the key:
['projects', { status }]. Changing the filter then starts a fresh infinite query frominitialPageParam. - Using
fetchNextPagefor refresh. It only appends. Userefetchor invalidation to reload the pages you have. - Duplicated items across pages. Offset-based APIs can return the same item twice if rows are inserted while the user scrolls. Prefer cursors, or remove duplicates by
idwhen you flatten. - Wrong
getNextPageParamfor offset APIs. If the server returns only items, compute the next offset from the page count:allPages.length * pageSize. ReturnundefinedwhenlastPage.length < pageSize.
getNextPageParam: (lastPage, allPages) =>
lastPage.length < 20 ? undefined : allPages.length * 20,Exercise
Your infinite list has 12 pages loaded. A mutation succeeds and calls invalidateQueries({ queryKey: ['projects'] }). What requests happen, and what two settings could reduce the cost?
Show answer
TanStack Query refetches all 12 loaded pages sequentially, starting with the first, because each page's parameter depends on the previous page's response. You can reduce the cost with maxPages, which caps how many pages stay cached, and with a longer staleTime, which cuts down on automatic refetches from focus and mount.
Exercise
A scroll sentinel calls fetchNextPage every time it intersects the viewport. Users report that the last page sometimes loads twice or flickers. What guard fixes it, and why?
Show answer
Only enable the observer when hasNextPage is true and isFetchingNextPage is false. Without it, a second call can cancel and restart the in-flight request, because fetchNextPage cancels a running fetch by default. It can also call the server after the final page has already loaded.