Paginate and load infinite queries
Choose pages or a growing list
A paginated catalogue shows one slice at a time; an infinite query can accumulate slices for a continuous list. A cursor is a token supplied by the data service to locate another slice, not necessarily a number. The following independent App.jsx files use TanStack Query v5 in a reviewed React/Vite project. The exact patch and dependencies are not locked yet. The fictional map catalogue contains three records and two pages; no external request is made. Read Chapter 24 first for query keys, errors and freshness.
import React, { useState } from 'react';import { QueryClient, QueryClientProvider, useQuery, useInfiniteQuery, useQueries, useMutation, useQueryClient, keepPreviousData, dehydrate, HydrationBoundary } from '@tanstack/react-query';function readPage(cursor) { const pages = {'start':{items:[{id:'a',name:'Atlas'},{id:'b',name:'Beacon'}],next:'second'},'second':{items:[{id:'c',name:'Compass'}],next:null}}; if (!Object.hasOwn(pages,cursor)) throw new Error('Invalid cursor'); return pages[cursor];}function Panel() { const [cursor,setCursor]=useState('start'); const q=useQuery({queryKey:['map-page',cursor],queryFn:async()=>readPage(cursor),placeholderData:keepPreviousData}); return <section><h2>Map catalogue</h2><p role="status">{q.isPlaceholderData?'Showing previous page while loading':q.isFetching?'Loading page':''}</p> {q.isError && <p role="alert">Page unavailable.</p>} {q.data && <ul>{q.data.items.map(row=><li key={row.id}>{row.name}</li>)}</ul>} <button disabled={cursor==='start'} onClick={()=>setCursor('start')}>First page</button> <button disabled={q.isPlaceholderData || q.isFetching || !q.data?.next} onClick={()=>setCursor(q.data.next)}>Next page</button> </section>;}export default function App() { const [client] = useState(() => new QueryClient({defaultOptions:{queries:{retry:false,refetchOnWindowFocus:false},mutations:{retry:false}}})); return <QueryClientProvider client={client}><Panel /></QueryClientProvider>;}Initially Atlas and Beacon appear; the next page contains Compass. A separate key is used for each cursor. Placeholder data temporarily displays a previous result, not a confirmed result for the new cursor. Disable forward navigation until the new cursor is known. In a real account or filter switch, retaining old results can leak data or mislead users; reset the observer or restrict placeholder reuse to the same scope. The instant mock may not show a visible transition.
Append pages with an infinite query
import React, { useState } from 'react';import { QueryClient, QueryClientProvider, useQuery, useInfiniteQuery, useQueries, useMutation, useQueryClient, keepPreviousData, dehydrate, HydrationBoundary } from '@tanstack/react-query';function readPage(cursor) { const pages = {'start':{items:[{id:'a',name:'Atlas'},{id:'b',name:'Beacon'}],next:'second'},'second':{items:[{id:'c',name:'Compass'}],next:null}}; if (!Object.hasOwn(pages,cursor)) throw new Error('Invalid cursor'); return pages[cursor];}function flattenPages(pages) { return pages.flatMap(page => page.items);}function Panel() { const q=useInfiniteQuery({queryKey:['map-feed'],queryFn:async({pageParam})=>readPage(pageParam),initialPageParam:'start',getNextPageParam:last=>last.next ?? undefined}); const rows=flattenPages(q.data?.pages ?? []); return <section><h2>All maps</h2>{q.isPending && <p role="status">Loading maps</p>}{q.isError && <p role="alert">Could not read maps.</p>} <ul>{rows.map(row=><li key={row.id}>{row.name}</li>)}</ul> <button disabled={!q.hasNextPage || q.isFetching} onClick={()=>q.fetchNextPage()}>Load more</button> <p role="status">{q.isFetchingNextPage?'Loading another page':q.data && !q.hasNextPage?'End of catalogue':''}</p> </section>;}export default function App() { const [client] = useState(() => new QueryClient({defaultOptions:{queries:{retry:false,refetchOnWindowFocus:false},mutations:{retry:false}}})); return <QueryClientProvider client={client}><Panel /></QueryClientProvider>;}After one successful append the list contains Atlas, Beacon, Compass. The cache keeps pages and pageParams under one infinite-query key; do not share that key with a normal query holding a different shape. The last cursor is null, translated to undefined so there is no further page. Guard against overlapping fetches while a refresh is active. Real mutable feeds can duplicate or omit items across pages; design stable ordering and deduplication with the service. Limit retained pages or use ordinary paging if the list grows large.
Combine independent reads and dependent reads
import React, { useState } from 'react';import { QueryClient, QueryClientProvider, useQuery, useInfiniteQuery, useQueries, useMutation, useQueryClient, keepPreviousData, dehydrate, HydrationBoundary } from '@tanstack/react-query';
function Panel() { const [selected,setSelected]=useState(''); const shelves=useQuery({queryKey:['shelf-ids'],queryFn:async()=>['east','west']}); const summaries=useQueries({queries:(shelves.data ?? []).map(id=>({queryKey:['summary',id],queryFn:async()=>({count:id==='east'?2:1})}))}); const detail=useQuery({queryKey:['detail',selected],enabled:!!selected && !!shelves.data?.includes(selected),queryFn:async()=>({label:selected==='east'?'East maps':'West maps'})}); return <section>{shelves.isError && <p role="alert">Shelves unavailable.</p>} <ul>{(shelves.data ?? []).map((id,i)=><li key={id}><button onClick={()=>setSelected(id)}>{id}</button> {summaries[i].isError?'Unavailable':summaries[i].data?.count ?? 'Waiting'}</li>)}</ul> {detail.isError && <p role="alert">Detail unavailable.</p>}{detail.data && <p>{detail.data.label}</p>} </section>;}export default function App() { const [client] = useState(() => new QueryClient({defaultOptions:{queries:{retry:false,refetchOnWindowFocus:false},mutations:{retry:false}}})); return <QueryClientProvider client={client}><Panel /></QueryClientProvider>;}Once shelf IDs arrive, both summary queries may proceed independently. Selecting East enables its detail read; the expected label is East maps. useQueries accepts a changing array of options, avoiding a changing number of Hook calls. Independent reads need not wait for each other. A genuinely dependent read must wait for its input, but if the backend can return the necessary information together it may avoid serial latency. A disabled query is not proof of authorization.
Practice
Predict each page, the final cursor, and the number of items after append. Explain why normal and infinite query keys must differ. Draw a dependency graph for shelf IDs, summaries and the selected detail.