
React Query example code is easiest to learn from when it solves a familiar interface problem. This article builds a paginated product list that keeps the previous page visible while the next one loads, prefetches ahead, and refreshes after a new product is added.
The example uses TanStack Query v5 with plain fetch calls, so you can drop it into any React 18 project. Each section explains why a line exists, not just what it does, which makes the pattern easy to adapt to tables, feeds or search results.
The API Shape
Assume an endpoint that accepts a page number and returns products plus a flag for more pages. Your backend may differ, but the client logic stays the same as long as the response says whether another page exists.
export async function fetchProducts(page) {
const res = await fetch(`/api/products?page=${page}`);
if (!res.ok) throw new Error('Failed to load products');
return res.json(); // { items: [...], hasMore: true }
}Building the Paginated Query
The page number lives in component state and is part of the query key. Every page becomes its own cache entry, so returning to a visited page is instant. The placeholderData option with the keepPreviousData helper shows the last page while the new one loads.
import { useQuery, keepPreviousData } from '@tanstack/react-query';
export function Products() {
const [page, setPage] = useState(1);
const { data, isPending, isError, isFetching, isPlaceholderData } = useQuery({
queryKey: ['products', page],
queryFn: () => fetchProducts(page),
placeholderData: keepPreviousData,
staleTime: 30_000,
});
if (isPending) return <p>Loading products…</p>;
if (isError) return <p>Products could not be loaded.</p>;
return (
<>
<ProductTable items={data.items} dimmed={isPlaceholderData} />
<button onClick={() => setPage((p) => Math.max(p - 1, 1))} disabled={page === 1}>Previous</button>
<span>Page {page}</span>
<button onClick={() => setPage((p) => p + 1)}
disabled={isPlaceholderData || !data.hasMore}>Next</button>
{isFetching && <small>Updating…</small>}
</>
);
}Why isPlaceholderData Matters
While the next page loads, data still holds the previous page. The isPlaceholderData flag tells you the visible rows are temporary, so the example dims the table and disables Next until real data arrives. Users never see an empty flash between pages.
Prefetching the Next Page
Prefetching requests the following page in the background so it is already cached when the user clicks. Run it in an effect that depends on the current page and the hasMore flag to avoid requesting pages that do not exist.
const queryClient = useQueryClient();
useEffect(() => {
if (!isPlaceholderData && data?.hasMore) {
queryClient.prefetchQuery({
queryKey: ['products', page + 1],
queryFn: () => fetchProducts(page + 1),
});
}
}, [data, isPlaceholderData, page, queryClient]);Adding a Product With a Mutation
A form that creates products should refresh every cached page, because the new item may change ordering. Invalidating the ['products'] prefix marks all page entries as stale and refetches the ones currently on screen.
const createProduct = useMutation({
mutationFn: (product) =>
fetch('/api/products', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(product),
}),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['products'] }),
});Prefix Matching Explained
Query invalidation matches keys by prefix. Passing ['products'] affects ['products', 1], ['products', 2] and any other key that starts the same way. This is why consistent, hierarchical keys pay off as an application grows.
Pagination Versus Infinite Scrolling
Numbered pages suit tables and admin screens, while feeds often use a load-more button. React Query supports both, using different hooks.
| Pattern | Hook | Cache structure |
|---|---|---|
| Numbered pages | useQuery | One entry per page |
| Load more or infinite scroll | useInfiniteQuery | One entry holding all pages |
For infinite lists, provide initialPageParam and getNextPageParam, then call fetchNextPage when the user scrolls. The rendering logic changes, but caching and invalidation work the same way.
Testing the Example
Open the React Query DevTools while clicking through pages. You should see one key per page, the prefetched key appearing early, and all product keys turning stale after a mutation.
- Throttle the network in browser tools to watch placeholder data.
- Switch tabs and return to observe focus refetching.
- Add a product and confirm the visible page updates.
Adding Filters and Search
Real product lists rarely show every item. Store the active category and search text in state, then place them in the query key alongside the page number. Each unique combination receives its own cache entry, so switching back to an earlier filter shows results instantly.
Search input changes on every keystroke, which could trigger many requests. Debounce the search value before it reaches the key, so the query only runs after the user pauses typing. The placeholder data pattern keeps old results visible while the new search loads.
const [filters, setFilters] = useState({ category: 'all', search: '' });
const search = useDebouncedValue(filters.search, 300);
useQuery({
queryKey: ['products', { page, category: filters.category, search }],
queryFn: () => fetchProducts({ page, ...filters, search }),
placeholderData: keepPreviousData,
});Showing Loading and Error States Well
The first visit to the list has no cached data, so a skeleton table works better than a blank area. Later page changes keep the previous rows visible, which is why the example only shows a small updating label during background requests.
Errors deserve a clear message and a retry button connected to the refetch function. Avoid replacing the whole table with an error if older data is still available. Showing the cached rows with a warning banner keeps the screen useful while the network recovers.
Making the Example Production Ready
- Move fetchProducts and the keys into a shared products module.
- Add a staleTime that matches how often your catalog changes.
- Reset the page to one when filters change.
- Cover empty results with a friendly message.
Switching the Example to Infinite Scrolling
Converting the list to a load-more feed replaces useQuery with useInfiniteQuery. The query function receives a pageParam, initialPageParam sets the first value and getNextPageParam reads the next cursor from the last response, returning undefined when no pages remain.
Rendering flattens data.pages into one array, and a button or intersection observer calls fetchNextPage. The hasNextPage and isFetchingNextPage flags drive the button label, so users always know whether more products are available and whether a request is running.
Choosing Between the Two Patterns
Numbered pages help users return to a precise position and share links, which suits admin tables. Infinite feeds suit browsing on mobile screens. Both rely on the same caching rules, so switching later does not require rethinking invalidation. Invalidating the ['products'] prefix refreshes either structure in exactly the same way.
React Query Example FAQ
Does keepPreviousData still exist in v5?
The keepPreviousData option was removed, but a helper function with that name is exported for use with placeholderData, as shown above.
Can this example use Axios?
Yes. Replace fetch with Axios calls in fetchProducts and the mutation. Axios rejects failed status codes automatically, so the manual check can go.
How do I reset to page one after filtering?
Store filters in the key, for example ['products', { page, category }], and set the page back to one whenever a filter changes.
Conclusion
React Query example patterns like this one cover most list screens: variables in keys, placeholder data for smooth transitions, prefetching for speed and prefix invalidation after writes.
Reuse the structure for orders, invoices or search results, and keep the caching guide nearby when tuning staleTime for each resource.



