Written by Huifer, solo developer and maintainer of TanStack Ship. I standardized query keys, freshness defaults, invalidation, and rollback behavior while maintaining several TanStack Start SaaS applications. The recurring failure was not that TanStack Query was slow; it was that each screen had a different cache contract. This guide turns those lessons into decisions you can test, not universal numbers.
Official references: TanStack Query documentation · Query keys · Important defaults · Mutations Last updated: 2026-10-25 · Changelog
TanStack Query Best Practices: Production Guide
Definition: TanStack Query best practices are production patterns for identity, freshness, retention, mutation consistency, and failure handling in server state. They are useful when the client owns a cache; they are not a replacement for server authorization, database transactions, or a real-time transport.
The decision rule I use: define the data's volatility, define the cost of stale data, define the mutation recovery path, then choose staleTime, gcTime, refetch triggers, and invalidation. If you choose options first and data semantics second, the cache contract becomes accidental.
Definition: TanStack Query best practices are patterns for giving each server-state query a stable identity, choosing deliberate freshness and retention policies, handling updates and failures consistently, and verifying cache behavior in the contexts where the application runs. They are not universal timeout values: freshness, retries, prefetching, and invalidation should reflect the data and user experience of each feature.
TL;DR: Build hierarchical query-key factories; choose staleTime based on acceptable data age and understand that gcTime controls inactive-cache retention. Prefetch only likely-to-be-used data. After mutations, update or invalidate the right cache entries and handle rollback carefully. For SSR, create a QueryClient per request, prefetch and dehydrate on the server, then hydrate the client. Render distinct pending, empty, and error states. Test cache transitions, and observe failures without logging sensitive query data.
1. Query key factories: make cache identity explicit
A query key identifies the data in the cache. Include every variable that changes the returned result (such as user, filter, locale, or page cursor); otherwise distinct requests can incorrectly share data. Keep related keys hierarchical so a mutation can invalidate one detail, one collection, or a broader entity family. Use plain serializable values in keys and avoid secrets or personally identifying data.
export const projectKeys = {
all: ['projects'] as const,
lists: () => [...projectKeys.all, 'list'] as const,
list: (filters: { status?: string; ownerId?: string }) =>
[...projectKeys.lists(), filters] as const,
details: () => [...projectKeys.all, 'detail'] as const,
detail: (projectId: string) =>
[...projectKeys.details(), projectId] as const,
activity: (projectId: string) =>
[...projectKeys.detail(projectId), 'activity'] as const,
}
async function fetchProject(projectId: string) {
const response = await fetch(`/api/projects/${encodeURIComponent(projectId)}`)
if (!response.ok) throw new Error(`Project request failed: ${response.status}`)
return response.json() as Promise<{ id: string; name: string }>
}
const projectQuery = (projectId: string) => ({
queryKey: projectKeys.detail(projectId),
queryFn: () => fetchProject(projectId),
})
Reuse the same key and query options in components, prefetches, and tests. If using a key factory adds more indirection than value to a tiny one-query screen, a consistent inline key is fine; the goal is stable identity, not abstraction for its own sake. See the official query key guide.
2. staleTime and gcTime solve different problems
staleTime determines how long data is considered fresh. Once stale, configured triggers such as remount, focus, reconnect, or explicit invalidation may cause a refetch. gcTime determines how long an inactive query remains in memory before garbage collection; it is not a freshness duration and does not evict an actively observed query. Choose per feature, with a moderate application default only if it suits most data. Infinity can be appropriate for immutable data that is updated through explicit invalidation; it is not appropriate when changes must become visible automatically.
| Data / interaction | Freshness starting point | Retention and refetch consideration | Avoid this when |
|---|---|---|---|
| Frequently changing status or live view | Short staleTime or 0 | Use polling, focus, or push updates only if the product needs them | Requests are costly or stale display is acceptable |
| Typical editable detail | A short, product-appropriate staleTime | Invalidate/update after successful writes; keep inactive data for useful back-navigation | There is no reliable update/invalidation path |
| Reference data that rarely changes | Longer staleTime | Explicitly invalidate on deployment or change if needed | The source can change without notifying the client |
| Immutable versioned content | Infinity can fit | Cache identity can include the content version | Data is mutable but invalidation is not guaranteed |
import { QueryClient } from '@tanstack/react-query'
export const createQueryClient = () =>
new QueryClient({
defaultOptions: {
queries: {
staleTime: 30_000, // Example default only; tune by feature.
gcTime: 5 * 60_000,
retry: (failureCount, error) => {
// Do not retry client errors such as not-found/validation responses.
if (error instanceof HttpError && error.status >= 400 && error.status < 500) {
return false
}
return failureCount < 2
},
},
mutations: { retry: 0 },
},
})
HttpError is an application error type that should expose an HTTP status; adapt the predicate to your API. Retries are not a substitute for handling authorization, validation, or not-found errors. Avoid a global default that disables all refetches or retries without reviewing every feature. Read TanStack Query's important defaults before overriding them.
3. Prefetch when there is a credible path to use
Prefetching can move work ahead of navigation, but it also consumes network, server, and memory resources. Prefer route-level or intent-based prefetch for likely next destinations, and use the same query key/options the destination consumes. TanStack Router can preload route data; if the route uses TanStack Query, coordinate the router and query caches so they do not both own the same server data unintentionally. Do not prefetch every item in a long list or on every pointer event.
import { useQueryClient } from '@tanstack/react-query'
function ProjectLink({ projectId, children }: {
projectId: string
children: React.ReactNode
}) {
const queryClient = useQueryClient()
function prefetchProject() {
void queryClient.prefetchQuery({
...projectQuery(projectId),
staleTime: 30_000,
})
}
return (
<a
href={`/projects/${encodeURIComponent(projectId)}`}
onPointerEnter={prefetchProject}
onFocus={prefetchProject}
>
{children}
</a>
)
}
This example uses a plain anchor to keep it framework-neutral. With TanStack Router use its Link and route preloading APIs where appropriate. Skip speculative prefetch on constrained connections, for low-probability destinations, or when server cost outweighs the likely navigation benefit. Prefetching warms the cache; it does not guarantee instant navigation.
4. Mutations, optimistic updates, rollback, and invalidation
After a successful write, either update a known cache value directly or invalidate affected queries so active observers can refetch. Use optimistic updates only when the UI benefits and the previous value can be restored. Cancel a pending fetch before changing its cache entry so an older response does not overwrite the optimistic state. Rollback is simplest when writes to the same entity are serialized; concurrent optimistic writes need an explicit conflict strategy.
import { useMutation, useQueryClient } from '@tanstack/react-query'
function useRenameProject(projectId: string) {
const queryClient = useQueryClient()
const detailKey = projectKeys.detail(projectId)
return useMutation({
mutationFn: async (name: string) => {
const response = await fetch(`/api/projects/${encodeURIComponent(projectId)}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name }),
})
if (!response.ok) throw new Error(`Rename failed: ${response.status}`)
return response.json() as Promise<{ id: string; name: string }>
},
onMutate: async (name) => {
await queryClient.cancelQueries({ queryKey: detailKey })
const previous = queryClient.getQueryData<{ id: string; name: string }>(detailKey)
if (previous) queryClient.setQueryData(detailKey, { ...previous, name })
return { previous }
},
onError: (_error, _name, context) => {
if (context?.previous) queryClient.setQueryData(detailKey, context.previous)
},
onSettled: () => {
// Reconcile with server truth, including after rollback.
void queryClient.invalidateQueries({ queryKey: detailKey })
void queryClient.invalidateQueries({ queryKey: projectKeys.lists() })
},
})
}
Do not optimistically change cache data if the server can reject the action for reasons the UI cannot predict, unless the rollback and conflict behavior are clear. If the mutation response is authoritative and its shape is known, setQueryData can avoid an unnecessary fetch; still invalidate dependent lists or aggregates that cannot be derived safely. Avoid invalidating the entire cache for a localized write. Official reference: mutations and query invalidation.
5. SSR and hydration
For server rendering, create a fresh QueryClient for each request. A module-global server QueryClient can leak cached data across requests. Prefetch the data required for the response, dehydrate it into the HTML, and hydrate a client QueryClient from that state. Server and browser settings should have intentional freshness semantics; they do not need to be described as a magic matching number. A positive staleTime often avoids an immediate client refetch of freshly prefetched data, while stale data may refetch according to normal rules.
// Server request: create this inside the request/render function, not at module scope.
import { dehydrate } from '@tanstack/react-query'
async function loadProjectPage(projectId: string) {
const queryClient = createQueryClient()
await queryClient.prefetchQuery(projectQuery(projectId))
return dehydrate(queryClient)
}
// Client root: provide the request's dehydrated state to the browser query cache.
import {
HydrationBoundary,
QueryClientProvider,
type DehydratedState,
} from '@tanstack/react-query'
import { useState } from 'react'
function App({ dehydratedState }: { dehydratedState: unknown }) {
const [queryClient] = useState(() => createQueryClient())
return (
<QueryClientProvider client={queryClient}>
<HydrationBoundary state={dehydratedState as DehydratedState}>
<ProjectPage />
</HydrationBoundary>
</QueryClientProvider>
)
}
Import the DehydratedState type from @tanstack/react-query for the prop in a real application; the cast above marks the boundary where your server framework provides serialized hydration data. In TanStack Start, use the framework's request/render lifecycle and the official TanStack Query SSR guide; ensure query functions are safe in the environment where they run and avoid serializing secrets. Do not add SSR hydration when the data is strictly client-only or when the added server work does not serve a product requirement.
6. Loading, empty, and error states
A query can be pending, successful with no results, successful with data, or errored; background refetching can also happen while usable data is present. Model these cases separately instead of replacing useful content with a full-screen spinner on every refetch. For retryable errors show a recovery action; for authorization or validation failures show an appropriate state rather than retrying blindly.
function ProjectPanel({ projectId }: { projectId: string }) {
const query = useQuery({
...projectQuery(projectId),
retry: false, // This screen offers an explicit retry path.
})
if (query.isPending) return <p role="status">Loading project…</p>
if (query.isError) {
return (
<section role="alert">
<p>Project could not be loaded.</p>
<button onClick={() => void query.refetch()}>Try again</button>
</section>
)
}
return (
<section aria-busy={query.isFetching}>
<h1>{query.data.name}</h1>
{query.isFetching && <p role="status">Refreshing…</p>}
</section>
)
}
Do not suppress error states for queries that have no cached data, and do not let a background refresh erase content the user can still read. For collection screens, add a distinct empty state after successful loading; it is not the same as an error or pending state.
7. Infinite queries: cursor, page shape, and boundaries
Use useInfiniteQuery when the interface genuinely loads a sequence of pages (for example, “load more” or a feed). Keep each page's continuation token in pageParam, return undefined when there is no next page, and expose disabled/loading/error states for the next-page request. Do not use an infinite query for a small, bounded list or when the user needs addressable page numbers and random access; ordinary paginated queries may fit better.
import { useInfiniteQuery } from '@tanstack/react-query'
type EventPage = { items: Array<{ id: string; label: string }>; nextCursor?: string }
function EventFeed() {
const events = useInfiniteQuery({
queryKey: ['events', 'feed'],
initialPageParam: undefined as string | undefined,
queryFn: async ({ pageParam }): Promise<EventPage> => {
const url = new URL('/api/events', window.location.origin)
if (pageParam) url.searchParams.set('cursor', pageParam)
const response = await fetch(url)
if (!response.ok) throw new Error(`Events request failed: ${response.status}`)
return response.json() as Promise<EventPage>
},
getNextPageParam: (lastPage) => lastPage.nextCursor,
})
if (events.isPending) return <p role="status">Loading events…</p>
if (events.isError) return <p role="alert">Events could not be loaded.</p>
return (
<>
{events.data.pages.flatMap((page) => page.items).map((event) => (
<article key={event.id}>{event.label}</article>
))}
<button
disabled={!events.hasNextPage || events.isFetchingNextPage}
onClick={() => void events.fetchNextPage()}
>
{events.isFetchingNextPage ? 'Loading…' : events.hasNextPage ? 'Load more' : 'End of list'}
</button>
</>
)
}
The example's window.location.origin makes this component browser-oriented; for SSR, use a request-aware base URL or a server-safe API client. Reset or vary the query key when feed filters change. Consider memory growth and the UX of retaining loaded pages for long sessions.
8. Test cache behavior; observe production failures
Test query behavior at the boundary that matters: query function success/failure, pending-to-success UI, mutation cache reconciliation, and the SSR hydration path if the application renders on the server. Use a fresh QueryClient for each test and disable retries in test defaults so failures are deterministic. Keep tests focused on user-visible behavior and cache invariants rather than implementation details.
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen } from '@testing-library/react'
import { describe, expect, it } from 'vitest'
function renderWithQueryClient(ui: React.ReactElement) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
return render(
<QueryClientProvider client={queryClient}>{ui}</QueryClientProvider>,
)
}
describe('ProjectPanel', () => {
it('renders a loading state before the request resolves', () => {
renderWithQueryClient(<ProjectPanel projectId="example" />)
expect(screen.getByRole('status')).toHaveTextContent('Loading project')
})
})
Mock the API request in the test environment and add separate success/error cases; the snippet is a harness example, not a complete test suite. For production observability, track request failures, latency, retry counts, and user-visible error rates through your existing telemetry. TanStack Query's QueryCache and MutationCache callbacks or cache subscriptions can be integration points, but avoid logging query variables, response bodies, or identifiers that contain sensitive information. Use TanStack Query Devtools during development to inspect keys, freshness, observers, and refetches; do not expose development tooling or raw cached data publicly.
Failure boundaries and limitations
These patterns do not solve every data problem. Do not use optimistic updates for irreversible payments unless the UI clearly represents a pending state and the server remains authoritative. Do not use staleTime: Infinity for mutable permissions, inventory, or billing entitlements unless an explicit invalidation path is guaranteed. Do not log full query keys when they contain customer identifiers, tokens, or search terms. TanStack Query caches server responses; it does not make an unsafe endpoint safe.
In my own review workflow, I verify the cache contract with a small matrix: cold mount, back navigation, focus after a mutation, failed mutation, expired session, and two browser tabs editing the same record. A passing unit test is not proof that two tabs cannot race; it only proves the modeled transition.
If you want a working base instead of wiring this yourself, the TanStack Ship templates include auth, billing, and deployment already set up.
Production checklist
- Query keys include every input that changes the response; related keys have deliberate invalidation boundaries.
-
staleTimeexpresses acceptable staleness;gcTimeis chosen for inactive cache retention, not as a freshness control. - Retry behavior distinguishes transient failures from permanent client errors.
- Prefetching is limited to likely next actions and reuses the destination's key/options.
- Mutation success updates or invalidates the affected detail, list, and dependent data; rollback behavior is defined for conflicts.
- SSR uses a request-scoped QueryClient and transfers only data safe to serialize.
- UI distinguishes pending, empty, error, and background-fetch states.
- Infinite-query cursor and end-of-list behavior are tested; pagination type matches the interaction.
- Tests use isolated clients and cover important cache transitions; production telemetry avoids sensitive query data.
Related reading: TanStack Query v5 guide · TanStack Router best practices · TanStack Query WebSocket real-time guide · TanStack Start SEO guide
Official references: TanStack Query overview · Query keys · Query invalidation · SSR · Infinite queries