Written by Huifer, solo developer and maintainer of TanStack Ship. I have shipped production apps using TanStack Query v5 (formerly React Query) across multiple SaaS products. These guides reflect first-hand production experience with real code, measured behavior, and honest limitations.
Verified sources: tanstack.com, github.com/TanStack, web.dev, developers.mozilla.org. Last updated: 2026-10-27 · Changelog
TanStack Query (formerly React Query) v5 introduced significant API improvements and performance enhancements. After shipping dozens of production apps with it, here are the patterns that actually work at scale. This TanStack Query best practices guide was last updated on 2026-10-27 to keep the migration and production patterns current.
TL;DR: v5 is a cleanup release.
cacheTimebecamegcTime,notifyOnChangePropsandisDatawere removed, anduseQuerylost itsonError/onSuccesscallbacks. Migrate in this order: package →gcTime→notifyOnChangeProps→isData→ SSR hydration → test suite. Then adopt the v5-idiomatic patterns: query key factories,queryOptions(), intentionalstaleTime,select-based fine-grained subscriptions, and optimistic mutations that always roll back.
2026 Update: What Has Changed
This article was first published for the v5 release and remains the most complete TanStack Query best practices reference on this site. As of 2026-10-27, the core guidance has not needed revision — v5 is a stabilization release, and its breaking changes and idiomatic patterns are still current. This update restates the data points that matter most and confirms they still hold.
The headline breaking changes are unchanged. cacheTime was renamed to gcTime and the old name is removed entirely, so a project-wide search-and-replace is still the first migration step. notifyOnChangeProps was removed in favour of select-based fine-grained subscriptions, and isData was removed in favour of explicit isSuccess / isError status flags. useQuery no longer accepts onSuccess / onError callbacks — those now live on useMutation, or you use throwOnError with an error boundary. keepPreviousData: true moved to placeholderData: keepPreviousData, and Suspense split out into its own useSuspenseQuery hook. The full list of removed APIs is tracked in the official migrating-to-v5 guide.
The recommended migration order is also unchanged: package → gcTime → notifyOnChangeProps → isData → SSR hydration → test suite. Doing them in this sequence keeps the runtime warnings actionable instead of turning into a bug hunt.
The production patterns we recommend — structured query key factories, reusable queryOptions(), intentional staleTime values, select-based subscriptions, and optimistic mutations that always roll back on onError and re-fetch on onSettled — remain the same. For the route-loader integration with queryOptions(), see our TanStack Router best practices. For any API detail beyond this summary, the official TanStack Query v5 docs and the migration guide remain the authoritative references.
TanStack Query v5 Best Practices: What Changed
v5 is primarily a cleanup and stabilization release. The v4 API had several deprecated paths that the team had intended to remove for two major versions. v5 is when those removals land.
| Change | Old (v4) | New (v5) | Impact |
|---|---|---|---|
| Cache garbage collection time | cacheTime | gcTime | Renamed — cacheTime is removed in v5 |
| Re-render control | notifyOnChangeProps | select | Removed; select is the idiomatic replacement |
| Boolean data shortcut | query.isData | query.isSuccess | Removed; use explicit status flags |
| Keep previous page data | keepPreviousData: true | placeholderData: keepPreviousData | Moved to the placeholderData option |
| Success/error callbacks | onSuccess / onError on useQuery | none | Use throwOnError + error boundaries |
| Suspense | useQuery({ suspense: true }) | useSuspenseQuery | Split into its own hook |
Source: the official migrating-to-v5 guide.
The gcTime rename
cacheTime was soft-renamed to gcTime in v4. In v5 it is removed entirely:
// v4 (deprecated in v4, removed in v5)
const { data } = useQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
cacheTime: 5 * 60 * 1000, // ❌ Removed in v5
});
// v5
const { data } = useQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
gcTime: 5 * 60 * 1000, // ✅ Correct in v5
});
notifyOnChangeProps is gone
The option that let you pick which result properties trigger a re-render was removed in favour of fine-grained subscriptions via select:
// v4 — notifyOnChangeProps (removed in v5)
const { data } = useQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
notifyOnChangeProps: ['data', 'error'], // ❌ Removed
});
// v5 — subscribe to a slice instead
const { data: todoCount } = useQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
select: (data) => data.length, // ✅ Only re-renders when length changes
});
select existed in v4 too, but in v5 it becomes the supported way to avoid unnecessary re-renders.
TanStack Query v5 Best Practices: Migration Checklist
Run through these steps in order — skipping one turns a clean migration into a runtime bug hunt.
- Update the package to
tanstack-query@5.xand confirm the React peer dependency (v5 requires React 18+). - Replace every
cacheTimewithgcTime(project-wide search). - Convert every
notifyOnChangePropstoselect, or drop it if the default re-render behaviour is acceptable. - Replace
isDatawithisSuccess/isError/isLoading. - Move
onSuccess/onErroroffuseQuery— they now live onuseMutation, or you usethrowOnErrorwith an error boundary. - Swap
keepPreviousData: trueforplaceholderData: keepPreviousData. - Test SSR hydration if you use
dehydrate/HydrationBoundary. - Run the test suite and read the console — v5 emits migration warnings for every removed API.
Step-by-Step Migration
Step 1: Update the package
npm install @tanstack/react-query@5
# or
pnpm add @tanstack/react-query@5
Step 2: Update the QueryClient defaults
// src/lib/queryClient.ts
import { QueryClient } from '@tanstack/react-query';
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
gcTime: 1000 * 60 * 5, // 5 minutes (was cacheTime)
staleTime: 1000 * 30, // 30 seconds — a sane default
retry: 1,
refetchOnWindowFocus: true,
},
mutations: {
onError: (error) => {
console.error('Mutation error:', error);
},
},
},
});
Step 3: Adopt the query key factory pattern
Centralising keys is what keeps invalidation predictable once a codebase grows past a handful of queries:
// src/lib/queryKeys.ts
export const queryKeys = {
users: {
all: ['users'] as const,
lists: () => [...queryKeys.users.all, 'list'] as const,
list: (filters: UserFilters) => [...queryKeys.users.lists(), filters] as const,
details: () => [...queryKeys.users.all, 'detail'] as const,
detail: (id: string) => [...queryKeys.users.details(), id] as const,
},
} as const;
The same factory pattern, with domain-specific key groups:
// Usage in components
const { data: users } = useQuery({
queryKey: queryKeys.users.list({ status: 'active' }),
queryFn: () => fetchUsers({ status: 'active' }),
});
Step 4: Fine-grained reactivity with select
select is the v5 way to subscribe to a slice of query data — the component never re-renders for changes that don't affect it:
// Only the count matters here
const { data: userCount } = useQuery({
queryKey: queryKeys.users.all,
queryFn: fetchAllUsers,
select: (users) => users.length,
});
Step 5: SSR hydration (if applicable)
dehydrate and HydrationBoundary still work the same way; v5 simply tightened the types:
// app/page.tsx — Next.js App Router example
import { dehydrate, HydrationBoundary, QueryClient } from '@tanstack/react-query';
async function UsersPage() {
const queryClient = new QueryClient();
await queryClient.prefetchQuery({
queryKey: queryKeys.users.list({ status: 'active' }),
queryFn: () => fetchUsers({ status: 'active' }),
});
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<UsersList />
</HydrationBoundary>
);
}
Query Key Factories
The single most impactful pattern: structured query key factories. Ad-hoc string keys create subtle bugs and make cache invalidation unpredictable.
// queries/userKeys.ts
export const userKeys = {
all: ['users'] as const,
lists: () => [...userKeys.all, 'list'] as const,
list: (filters: UserFilters) => [...userKeys.lists(), filters] as const,
details: () => [...userKeys.all, 'detail'] as const,
detail: (id: string) => [...userKeys.details(), id] as const,
}
// Usage
const { data } = useQuery({
queryKey: userKeys.detail(userId),
queryFn: () => fetchUser(userId),
})
// Invalidate all user queries
queryClient.invalidateQueries({ queryKey: userKeys.all })
// Invalidate just the list
queryClient.invalidateQueries({ queryKey: userKeys.lists() })
Typed Query Options
v5 introduced queryOptions() for reusable, type-safe query configurations:
import { queryOptions } from '@tanstack/react-query'
export const userQueryOptions = (userId: string) =>
queryOptions({
queryKey: userKeys.detail(userId),
queryFn: () => fetchUser(userId),
staleTime: 5 * 60 * 1000, // 5 minutes
})
// In a component
const { data: user } = useQuery(userQueryOptions(userId))
// In a route loader (TanStack Router integration)
export const Route = createFileRoute('/users/$userId')({
loader: ({ context, params }) =>
context.queryClient.ensureQueryData(userQueryOptions(params.userId)),
})
Smart Stale Times and Caching
Don't use the default staleTime: 0 for everything when configuring your cache. Think about how often the cached data changes:
// User preferences rarely change — cache for 1 hour
const { data: preferences } = useQuery({
queryKey: ['preferences'],
queryFn: fetchPreferences,
staleTime: 60 * 60 * 1000,
})
// Feed data changes constantly — no cache
const { data: feed } = useQuery({
queryKey: ['feed'],
queryFn: fetchFeed,
staleTime: 0,
refetchInterval: 30_000,
})
// Product catalog — medium cache
const { data: products } = useQuery({
queryKey: ['products', filters],
queryFn: () => fetchProducts(filters),
staleTime: 5 * 60 * 1000,
})
staleTime: Infinity still works in v5 — it simply means "never consider this stale". Use it for reference data that changes on a deploy cadence, and disable the automatic refetch triggers explicitly if you want that guarantee.
Optimistic Mutations
Optimistic updates make your UI feel instant. v5 makes this much cleaner:
function useUpdateTodo() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: updateTodo,
onMutate: async (updatedTodo) => {
// Cancel in-flight queries to avoid overwriting optimistic update
await queryClient.cancelQueries({ queryKey: todoKeys.detail(updatedTodo.id) })
// Snapshot the previous value for rollback
const previous = queryClient.getQueryData(todoKeys.detail(updatedTodo.id))
// Optimistically update
queryClient.setQueryData(todoKeys.detail(updatedTodo.id), (old) => ({
...old,
...updatedTodo,
}))
return { previous }
},
onError: (err, updatedTodo, context) => {
// Rollback on failure
queryClient.setQueryData(todoKeys.detail(updatedTodo.id), context?.previous)
},
onSettled: (data, error, updatedTodo) => {
// Always refetch after mutation
queryClient.invalidateQueries({ queryKey: todoKeys.detail(updatedTodo.id) })
},
})
}
The onMutate → onError → onSettled trio is the whole contract: onMutate produces the optimistic state and returns the rollback context, onError restores that context, onSettled always invalidates so the next render reflects server truth.
Infinite Queries with Cursor Pagination
Cursor-based pagination is more reliable than offset pagination for live data:
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useInfiniteQuery({
queryKey: ['posts', filters],
queryFn: ({ pageParam }) => fetchPosts({ cursor: pageParam, ...filters }),
initialPageParam: undefined as string | undefined,
getNextPageParam: (lastPage) => lastPage.nextCursor,
})
// Flatten pages for rendering
const posts = data?.pages.flatMap((page) => page.items) ?? []
Error Boundaries Integration
Because v5 removed onError from useQuery, errors that should break the route are raised with throwOnError and caught by a boundary:
// Throw errors to nearest error boundary
const { data } = useQuery({
queryKey: ['critical-data'],
queryFn: fetchCriticalData,
throwOnError: true,
})
// In your route or component tree
function RouteErrorBoundary({ error }: { error: Error }) {
return (
<div className="error-state">
<h2>Something went wrong</h2>
<p>{error.message}</p>
<button onClick={() => window.location.reload()}>Retry</button>
</div>
)
}
Prefetching for UX
Prefetch data on hover to eliminate loading states entirely:
function PostCard({ post }: { post: Post }) {
const queryClient = useQueryClient()
return (
<Link
to="/posts/$postId"
params={{ postId: post.id }}
onMouseEnter={() => {
queryClient.prefetchQuery(postQueryOptions(post.id))
}}
>
{post.title}
</Link>
)
}
FAQ
What are the biggest breaking changes in TanStack Query v5?
cacheTime → gcTime (the old name is removed), notifyOnChangeProps removed in favour of select, isData removed in favour of explicit status flags, and useQuery no longer accepts onSuccess / onError.
How do I migrate from React Query v4 to v5?
Update the package, replace all cacheTime with gcTime, convert notifyOnChangeProps usage to select, replace isData checks, and run your test suite after each step. The official migration guide lists every removed API.
Does TanStack Query v5 work with Next.js App Router?
Yes. The QueryClient must be created client-side to avoid hydration mismatches, and HydrationBoundary + dehydrate work the same way as in v4.
Is staleTime: Infinity still supported?
Yes — it is not deprecated in v5. It means the data is never considered stale, so pair it with explicit refetchOnMount / refetchOnWindowFocus: false if you need a hard guarantee.
How does v5 improve performance over v4?
Through select-based fine-grained subscriptions (fewer re-renders in list views), a clearer gcTime / staleTime lifecycle, and refined query cancellation behaviour.
Related reading: Tanstack Router Best Practices 2026 · Tanstack Query Booking Holds · TanStack Query vs SWR
If you want a working base instead of wiring this yourself, the TanStack Ship templates include auth, billing, and deployment already set up.
Before committing to an approach, read the TanStack Query Best Practices: Production Guide — it collects the decision criteria, limits, and alternatives that this page only touches on.
Wrapping Up
The most important takeaways:
- Query key factories — structure your keys from day one
queryOptions()— share query config between components and loaders- Intentional stale times — match cache duration to data change frequency
- Optimistic updates — always handle rollback and re-fetch on settle
- Prefetch on hover — the cheapest performance win you'll ever find
These patterns have saved countless hours debugging stale data and cache invalidation bugs in production. Start with key factories and work from there.