QueryClient Defaults and Production Configuration
TanStack Query v5.59 sets staleTime to 0 by default, marking data as stale immediately. The gcTime defaults to 300000 ms. The built-in retry function attempts a query three times before failing. These defaults suit applications that require fresh data on every mount but increase network traffic in read-heavy interfaces.
Configure the QueryClient once at the root of your application. Create a provider file that exports both the client and a provider component. Set staleTime to 10000 for user profile data that changes infrequently. Use 0 for real-time metrics that must reflect backend state on every visit. Set gcTime to 900000 for expensive report queries so the cache survives browser tab switches.
Additional options include networkMode: 'online' which skips background refetches when the browser reports offline status. Combine with refetchOnMount: true to always validate data when a component mounts even if the cache holds a fresh copy. For apps using React 19, enable experimental_prefetchInRender in the QueryClient options to start prefetch work during render when possible.
Define mutation defaults at the QueryClient level to avoid repeating retry logic across useMutation calls. The following setup centralizes behavior for an entire SaaS application:
import { QueryClient } from '@tanstack/react-query';
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 0,
gcTime: 300000,
retry: (failureCount, error: any) => {
if (error?.status === 404) return false;
if (error?.status === 401) return false;
return failureCount < 3;
},
refetchOnWindowFocus: true,
networkMode: 'online',
},
mutations: {
retry: 1,
networkMode: 'online',
},
},
});
Wrap the application with QueryClientProvider and pass this client instance. This single source of configuration prevents divergent behavior between teams working on different modules. When backend rate limits are reached, the retry logic combined with exponential backoff prevents cascading failures. Adjust gcTime higher for mobile web apps where users switch tabs frequently and expect cached views to remain available.
Type-Safe Query Key Factories
Query keys must be arrays. Using plain string literals or inconsistent array shapes leads to cache misses and over-fetching. A factory object groups related keys, guarantees consistent prefixes, and gives TypeScript literal types for autocompletion and inference.
Define the factory with as const assertions so that each key retains its literal type. Include parameter objects at the end of the tuple so filters participate in cache identity. The structure supports both exact matches and prefix invalidation.
export const projectKeys = {
all: ['projects'] as const,
lists: () => [...projectKeys.all, 'list'] as const,
list: (filters: { status?: 'active' | 'archived'; teamId?: string; search?: string }) => [
...projectKeys.lists(),
filters,
] as const,
details: (projectId: string) => [...projectKeys.all, 'detail', projectId] as const,
summary: (projectId: string, period: '7d' | '30d' | '90d') => [
...projectKeys.details(projectId),
'summary',
period,
] as const,
tasks: (projectId: string, pageParam?: string) => [
...projectKeys.details(projectId),
'tasks',
{ pageParam },
] as const,
} as const;
export type ProjectKeys = typeof projectKeys;
With this factory, useQuery({ queryKey: projectKeys.list({ status: 'active' }) }) produces a typed key. Prefix invalidation works because invalidateQueries({ queryKey: projectKeys.lists() }) matches every list variant. For parallel queries, useQueries accepts an array generated from mapped factory calls.
Step-by-step creation process: first identify all query domains, then create an all entry, add list and detail variants, finally add parameterized variants for filters and pagination. Export the type for use in custom hooks. This approach scales to codebases with hundreds of queries while keeping invalidation logic concise. The deterministic nature of the array structure matches TanStack Query's internal hash function that converts the key into a stable string for Map lookup.
Hydration Patterns with Next.js 15 App Router
Next.js 15 allows server components to fetch data before rendering. TanStack Query runs on the client, so data must be serialized and rehydrated to avoid duplicate requests. The HydrationBoundary component from @tanstack/react-query restores cache state on the client.
Follow these steps in a server component: instantiate a fresh QueryClient, call prefetchQuery for each required query, pass the dehydrated state to HydrationBoundary. The client component then reads from cache without loading states on initial render.
// app/projects/page.tsx
import { dehydrate, HydrationBoundary, QueryClient } from '@tanstack/react-query';
import { projectKeys } from '@/lib/project-keys';
import ProjectList from './ProjectList';
async function ProjectsPage() {
const queryClient = new QueryClient();
await queryClient.prefetchQuery({
queryKey: projectKeys.list({ status: 'active' }),
queryFn: async () => {
const response = await fetch('https://api.example.com/projects?status=active', {
headers: { Authorization: `Bearer ${process.env.API_TOKEN}` },
});
if (!response.ok) throw new Error('Failed to fetch');
return response.json();
},
});
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<ProjectList />
</HydrationBoundary>
);
}
export default ProjectsPage;
On the client side ProjectList uses a standard useQuery with the identical queryKey. The framework reuses the server-fetched data. For dynamic routes that depend on URL parameters, read params in the server component and pass them to both the prefetch call and as props to the client component. When combining with streaming and React Suspense boundaries, place the HydrationBoundary inside a <Suspense> fallback to show a skeleton while the server fetch completes.
This pattern eliminates the flash of loading content on first visit. When the same page is revisited, the client cache takes over unless the staleTime has expired. The dehydrated payload contains only the query results and metadata; avoid prefetching massive binary data that would bloat the HTML.
Cursor-Based Infinite Queries for Feeds and Tables
Infinite queries maintain a growing list of pages. Cursor-based pagination returns a stable pointer instead of numeric offsets, avoiding duplication when records are added or removed between requests.
Implement with useInfiniteQuery, supplying initialPageParam, getNextPageParam, and optionally getPreviousPageParam. The query function receives the current pageParam from the previous response.
function ProjectFeed() {
const {
data,
fetchNextPage,
fetchPreviousPage,
hasNextPage,
hasPreviousPage,
isFetchingNextPage,
isFetchingPreviousPage,
} = useInfiniteQuery({
queryKey: projectKeys.lists(),
initialPageParam: null as string | null,
queryFn: async ({ pageParam }) => {
const url = new URL('/api/projects', window.location.origin);
if (pageParam) url.searchParams.set('cursor', pageParam);
url.searchParams.set('limit', '20');
const res = await fetch(url.toString());
if (!res.ok) throw new Error('Network error');
return res.json() as Promise<{
projects: Project[];
nextCursor: string | null;
prevCursor: string | null;
}>;
},
getNextPageParam: (lastPage) => lastPage.nextCursor,
getPreviousPageParam: (firstPage) => firstPage.prevCursor,
});
const allProjects = data?.pages.flatMap((page) => page.projects) ?? [];
return (
<div>
{hasPreviousPage && (
<button => fetchPreviousPage()} disabled={isFetchingPreviousPage}>
Load previous
</button>
)}
{allProjects.map((project) => (
<ProjectCard key={project.id} project={project} />
))}
{hasNextPage && (
<button
=> fetchNextPage()}
disabled={isFetchingNextPage}
>
{isFetchingNextPage ? 'Loading...' : 'Load more projects'}
</button>
)}
</div>
);
}
Use the Intersection Observer API to trigger fetchNextPage automatically when the user scrolls near the bottom. Store the observer in a useEffect that cleans up on unmount. The flatMap operation concatenates results from every page into a single array for rendering. Keep page data separate when individual page refreshes are required.
Trade-off: memory grows linearly with the number of loaded pages. After approximately ten pages the cache can hold several thousand objects. Use the maxPages option introduced in recent v5 releases to automatically drop old pages, or manually trim by calling queryClient.setQueryData with a sliced pages array after each successful fetch.
Optimistic Updates with Precise Rollback
Optimistic updates update the UI before the server responds. The onMutate hook runs before the mutation function, allowing snapshot of previous state. The context object carries that snapshot to onError for rollback.
Three concrete examples follow. First, adding a new project with a temporary ID:
const addMutation = useMutation({
mutationFn: (newProject: Omit<Project, 'id'>) =>
fetch('/api/projects', { method: 'POST', body: JSON.stringify(newProject) }).then(r => r.json()),
onMutate: async (newProject) => {
await queryClient.cancelQueries({ queryKey: projectKeys.lists() });
const previousList = queryClient.getQueryData(projectKeys.list({ status: 'active' }));
const tempId = `temp-${Date.now()}`;
const optimisticProject = { ...newProject, id: tempId, status: 'active' };
queryClient.setQueryData(projectKeys.list({ status: 'active' }), (old: any) => ({
...old,
projects: [...(old?.projects || []), optimisticProject],
}));
return { previousList, tempId };
},
onError: (err, newProject, context) => {
queryClient.setQueryData(projectKeys.list({ status: 'active' }), context?.previousList);
},
onSettled: (data, error, newProject, context) => {
if (context?.tempId) {
queryClient.invalidateQueries({ queryKey: projectKeys.lists() });
}
},
});
Second, updating an existing record requires targeting both the list cache and the detail cache. Third, deleting a record filters it from the list cache immediately and restores it on failure. Each setQueryData call must produce a new object or array reference so React Query and React correctly detect the change.
The sequence is: cancel ongoing queries to prevent race conditions, read current data, write optimistic data, return context, mutate on server, then either rollback or invalidate on settlement. This gives instant feedback while maintaining consistency if the server rejects the change. When the server returns the canonical record, the final invalidateQueries brings the exact server state into the cache.
Prefetching Strategies for Navigation and Search
queryClient.prefetchQuery and the newer queryClient.ensureQueryData start background work before a component mounts. Attach prefetch to link hover events, route change events, or debounced search inputs.
For a sidebar navigation component, define a hover handler that extracts the project ID and calls prefetchQuery using the detail key. The staleTime supplied to the prefetch call overrides the default so the data stays fresh longer than usual. In Next.js, combine with the Link component's prefetch prop for static routes while using manual prefetch for dynamic API-backed data.
For search autocomplete, debounce the input by 180 ms then call ensureQueryData. This function returns the data if already present or fetches it and returns the promise result. The search query key includes the search term so each unique term gets its own cache entry. After the user selects a result, the detail query for that item is already warm.
Global prefetch rules can be registered with queryClient.setQueryDefaults for entire key families. Monitor active prefetch calls with the QueryClient's subscription API to avoid firing more than three concurrent prefetches on slow networks.
Error Recovery and Retry Semantics
Define retry logic per query type. Critical mutations such as payment processing use retry: false. Non-critical list queries retry three times. Create typed error classes that the retry function can inspect.
Implement a global error handler by subscribing to the QueryCache events. On any query failure with status 401, trigger a logout flow. For mutations, useMutationState allows a component to observe the latest mutation for a given key and display a toast with recovery options such as "Retry now" that calls mutate() again with the same variables.
When using React 19, wrap error-prone queries in <ErrorBoundary> components that receive the reset function from TanStack Query to clear the error state and refetch. Combine with suspense: true in query options to let parent Suspense boundaries catch loading states uniformly.
Devtools and Observability Integration
Include <ReactQueryDevtools initialIsOpen={false} /> inside the provider. In production builds, conditionally render only when a specific URL flag such as ?devtools=true is present. The devtools panel shows query status, data age, and fetch times. Use the built-in filter to inspect only keys matching a project prefix.
For observability beyond development, subscribe to query cache events and forward metrics to your monitoring service. Log the number of active queries, cache size in bytes, and failed mutations. The queryClient.getQueryCache() method returns the internal cache object for inspection at any time.
Memory Tuning and Garbage Collection
Long-lived pages with many infinite queries accumulate data. Call queryClient.removeQueries({ queryKey: projectKeys.lists(), exact: false }) when a user navigates away from the projects section. Reduce gcTime to 120000 for feed data that becomes irrelevant quickly.
Listen to the updated and removed events on the query cache to track memory usage. When the total number of cached queries exceeds a threshold such as 80, run a cleanup that removes all queries older than their gcTime. For applications that support offline mode, persist selected queries to IndexedDB using the official TanStack Query persistence plugin and restore them on next visit.
Testing with MSW and QueryClientProvider
Tests require an isolated QueryClient that does not share state between test cases. Create a fresh client inside a custom render function. Mock network calls with MSW so that useQuery receives deterministic responses.
import { render, screen, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { setupServer } from 'msw/node';
import ProjectList from './ProjectList';
const createTestClient = () => new QueryClient({
defaultOptions: { queries: { retry: false } },
});
const server = setupServer(
rest.get('/api/projects', (req, res, ctx) =>
res(ctx.json({ projects: [{ id: '1', name: 'Test Project' }] }))
)
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
const customRender = (ui: React.ReactElement) => {
const testClient = createTestClient();
return render(
<QueryClientProvider client={testClient}>
{ui}
</QueryClientProvider>
);
};
test('renders project list after successful fetch', async () => {
customRender(<ProjectList />);
expect(screen.getByText('Loading projects...')).toBeInTheDocument();
await waitFor(() => {
expect(screen.getByText('Test Project')).toBeInTheDocument();
});
});
Additional tests cover error states by having MSW return a 500 response and asserting that the error UI appears. Test optimistic updates by firing the mutation and immediately checking that the UI reflects the optimistic value before the mocked response resolves. This suite catches stale query key bugs and incorrect context handling in rollback functions. Run tests with Vitest or Jest; the isolated client prevents pollution across parallel test files.
