TanStack Query Cache Not Invalidating— invalidateQueries Not Working [Fixed 2026]
Also covers: queryKey mismatch · onSuccess · partial key matching · setQueryData · optimistic updates · race conditions
⚡ The Problem
// Mutation succeeds — but the list doesn't update
const mutation = useMutation({
mutationFn: createPost,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["post"] }) // wrong key!
// The query uses ["posts"] — note the 's'
},
})✅ Fix — match queryKey exactly
// useQuery uses:
queryKey: ["posts"]
// invalidateQueries must use the same key:
queryClient.invalidateQueries({ queryKey: ["posts"] }) // ✅ matchesWhy invalidateQueries Silently Does Nothing
TanStack Query matches query keys using deep equality. If there is any difference between the key you pass to invalidateQueries and the key used in useQuery — a typo, different structure, different order of object properties — the invalidation silently matches nothing and no refetch occurs.
The second common cause is calling invalidateQueries outside of onSuccess, or without awaiting it, causing a race between the invalidation and the component's response to the mutation.
Match the queryKey Exactly
Root cause — key typo or structural mismatchCompare your useQuery key and your invalidateQueries key character by character. They must be identical arrays.
// ❌ Typo — "post" vs "posts"
useQuery({ queryKey: ["posts"], queryFn: fetchPosts })
queryClient.invalidateQueries({ queryKey: ["post"] }) // no match
// ❌ Wrong nesting — flat vs nested
useQuery({ queryKey: ["posts", userId], queryFn: ... })
queryClient.invalidateQueries({ queryKey: [["posts", userId]] }) // no match
// ❌ Object key — property order matters for some versions
useQuery({ queryKey: ["posts", { status: "published", userId }], queryFn: ... })
queryClient.invalidateQueries({ queryKey: ["posts", { userId, status: "published" }] })
// ✅ Use query key factories to avoid typos
export const postKeys = {
all: ["posts"] as const,
list: (filters?: object) => [...postKeys.all, filters] as const,
detail: (id: string) => [...postKeys.all, id] as const,
}
// In useQuery:
queryKey: postKeys.list({ userId })
// In invalidateQueries:
queryClient.invalidateQueries({ queryKey: postKeys.list({ userId }) })Use query key factory objects (like postKeys above) to centralise your key definitions. This eliminates typos and makes invalidation reliable — one source of truth for every query key.
Call invalidateQueries in onSuccess
Mutation succeeds but list doesn't updateAlways trigger cache invalidation inside onSuccess of useMutation . This guarantees the invalidation only happens after the server confirms success.
import { useMutation, useQueryClient } from "@tanstack/react-query"
import { postKeys } from "@/lib/query-keys"
export function useCreatePost() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async (newPost: { title: string; content: string }) => {
const res = await fetch("/api/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(newPost),
})
if (!res.ok) throw new Error("Failed to create post")
return res.json()
},
// ✅ Invalidate in onSuccess — runs only after confirmed success
onSuccess: async (createdPost) => {
// Invalidate the list — triggers refetch
await queryClient.invalidateQueries({ queryKey: postKeys.all })
// Optionally seed the individual post cache immediately
queryClient.setQueryData(postKeys.detail(createdPost.id), createdPost)
},
onError: (error) => {
console.error("Create post failed:", error)
},
})
}Use Partial Key Matching to Invalidate Related Queries
Invalidate multiple related queries at oncePassing a partial key to invalidateQueries invalidates all queries whose key starts with that array. Use this to invalidate a whole feature's queries after a mutation.
// Queries in your app:
// ["posts"] — post list
// ["posts", { status: "draft" }] — filtered post list
// ["posts", "abc123"] — single post detail
// ["posts", "abc123", "comments"] — post comments
// ✅ Invalidate ALL of the above with one call:
queryClient.invalidateQueries({ queryKey: ["posts"] })
// ✅ Invalidate only detail + comments (not lists):
queryClient.invalidateQueries({ queryKey: ["posts", postId] })
// ✅ Exact match only — does NOT invalidate children:
queryClient.invalidateQueries({
queryKey: ["posts"],
exact: true, // only matches ["posts"], not ["posts", anything]
})
// ✅ After delete — invalidate everything related to posts
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ["posts"] })
await queryClient.invalidateQueries({ queryKey: ["comments"] })
}Use setQueryData for Instant Optimistic Updates
UI lag after mutation — want instant feedbackInstead of waiting for a refetch, update the cache directly with setQueryData for instant UI response. Roll back with the snapshot if the mutation fails.
export function useToggleLike(postId: string) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (liked: boolean) =>
fetch(`/api/posts/${postId}/like`, {
method: liked ? "POST" : "DELETE",
}),
// onMutate runs BEFORE the mutation — save snapshot & optimistic update
onMutate: async (liked) => {
// Cancel in-flight refetches (prevent overwriting optimistic update)
await queryClient.cancelQueries({ queryKey: ["posts", postId] })
// Snapshot the previous value
const previousPost = queryClient.getQueryData(["posts", postId])
// Optimistically update the cache
queryClient.setQueryData(["posts", postId], (old: any) => ({
...old,
liked,
likeCount: liked ? old.likeCount + 1 : old.likeCount - 1,
}))
// Return context for rollback
return { previousPost }
},
// onError — rollback to snapshot
onError: (err, liked, context) => {
queryClient.setQueryData(["posts", postId], context?.previousPost)
},
// onSettled — always sync with server after mutation
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ["posts", postId] })
},
})
}Await invalidateQueries to Prevent Race Conditions
Query updates before mutation response arrivesIf you do not await invalidateQueries , the component may re-render and read stale data before the refetch completes. Awaiting ensures the refetch finishes before onSuccess returns.
// ❌ Race condition — invalidation fires but doesn't wait for refetch
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["posts"] })
router.push("/posts") // navigates before refetch finishes — stale data shown
}
// ✅ Await the invalidation — refetch finishes before navigation
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ["posts"] })
router.push("/posts") // navigates after fresh data is in cache
}
// ✅ Or use onSettled to always invalidate (success or error):
onSettled: async () => {
await queryClient.invalidateQueries({ queryKey: ["posts"] })
}Awaiting invalidateQueries waits for the refetch to complete. This adds a brief delay before onSuccess finishes. For most UIs this is fine. For instant feedback, combine with an optimistic update (Fix 4) so the UI updates immediately while the refetch happens in background.
Prevention
- Use query key factory objects (e.g. postKeys) — one source of truth for all key strings, eliminates typos
- Always call invalidateQueries inside onSuccess or onSettled of useMutation — never ad hoc
- Await invalidateQueries in onSuccess to prevent race conditions before navigation
- Use partial key matching to invalidate an entire feature's queries with a single call
- Install ReactQueryDevtools — inspect which queries are active and when they refetch
- For instant UI updates, combine optimistic setQueryData with invalidation in onSettled as the sync step
Frequently Asked Questions
Why does invalidateQueries not trigger a refetch?+−
Where should I call invalidateQueries after a mutation?+−
What is the difference between invalidateQueries and refetchQueries?+−
How do I invalidate all queries for a feature at once?+−
What is an optimistic update in TanStack Query?+−
Should I use invalidateQueries or setQueryData after a mutation?+−
Need Expert Help?
We Build React Apps with TanStack Query
Softplix engineers implement TanStack Query with optimistic updates, key factories, and mutation pipelines for production React apps. Let us help.
Talk to an Engineer