TanStack Query Infinite Cursor Pagination

Drive cursor-based infinite lists with TanStack Query useInfiniteQuery, threading nextCursor through pages and prefetching ahead of scroll.

TypescriptReactData Fetching

Code

typescriptsnippet
52 lines
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-query is a real dependency, resolved by the package manager.
  • fetch exist only in browsers — a Node runtime has no shims for them out of the box.
  • The guard !res.ok short-circuits the flow with an early throw when 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

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.