TanStack Query Infinite Cursor Pagination
Drive cursor-based infinite lists with TanStack Query useInfiniteQuery, threading nextCursor through pages and prefetching ahead of scroll.
Code
import {
useInfiniteQuery, queryClient, keepPreviousData,
} from '@tanstack/react-query';
interface FeedPage {
items: { id: string; title: string }[];
nextCursor: string | null;
}
async function fetchFeed(cursor?: string): Promise<FeedPage> {
const params = new URLSearchParams({ limit: '20' });
if (cursor) params.set('cursor', cursor);
const res = await fetch('/api/feed?' + params.toString());
if (!res.ok) throw new Error('feed failed: ' + res.status);
return res.json();
}
function useFeed() {
return useInfiniteQuery({
queryKey: ['feed'],
queryFn: ({ pageParam }) => fetchFeed(pageParam),
initialPageParam: undefined as string | undefined,
getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
staleTime: 30_000,
placeholderData: keepPreviousData,
});
}
function FeedList() {
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useFeed();
const items = data?.pages.flatMap((page) => page.items) ?? [];
return (
<section>
{items.map((item) => <article key={item.id}>{item.title}</article>)}
<button
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetchingNextPage}
>
{isFetchingNextPage ? 'loading…' : 'load more'}
</button>
</section>
);
}
queryClient.prefetchInfiniteQuery({
queryKey: ['feed'],
queryFn: ({ pageParam }) => fetchFeed(pageParam),
initialPageParam: undefined as string | undefined,
pages: 1,
});Inside the snippet
TanStack Query Infinite Cursor Pagination keeps everything in the functions fetchFeed, useFeed and FeedList.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. useInfiniteQuery, queryClient, keepPreviousData are the only symbols borrowed from @tanstack/react-query — the coupling is explicit and narrow. The failure path is explicit — Error is raised when the guard condition holds.
What to watch for
- Plan for an install step:
@tanstack/react-queryis a real dependency, resolved by the package manager. fetchexist only in browsers — a Node runtime has no shims for them out of the box.- The guard
!res.okshort-circuits the flow with an earlythrowwhen its condition holds.
Using it
The entry-point signature is async function fetchFeed(cursor?: string)
Key statements
const items = data?.pages.flatMap((page) => page.items) ?? [];
{items.map((item) => <article key={item.id}>{item.title}</article>)}
async function fetchFeed(cursor?: string): Promise<FeedPage> {
const params = new URLSearchParams({ limit: '20' });
if (cursor) params.set('cursor', cursor);
const res = await fetch('/api/feed?' + params.toString());
if (!res.ok) throw new Error('feed failed: ' + res.status);
return res.json();
}
Interactive Tools for This Topic
GraphQL Query FormatterPretty-print a GraphQL query by indenting selection sets by brace depth and normalizing punctuation spacing.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.Query String ParserParse a query string or URL into decoded key-value rows, preserving repeated keys and empty values for debugging and API work.URL Query String SerializerParse a URL query string into decoded key/value pairs or serialize key=value lines into a percent-encoded query string with duplicate-key detection.
FAQ
- Is there a failure path for bad input?
- It throws `Error` before any real work runs, via the guard `!res.ok` — handle it at the call site or let it propagate deliberately.
- Does this require external packages?
- Yes — `@tanstack/react-query`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.