TanStack QueryReact QueryError Fix2026 Updated

TanStack Query Cache Not Invalidating— invalidateQueries Not Working [Fixed 2026]

Also covers: queryKey mismatch · onSuccess · partial key matching · setQueryData · optimistic updates · race conditions

January 20266 min readTanStack Query v5 · React · TypeScript

⚡ The Problem

Error
// 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

Correct — key must match useQuery exactly
// useQuery uses:
queryKey: ["posts"]

// invalidateQueries must use the same key:
queryClient.invalidateQueries({ queryKey: ["posts"] })  // ✅ matches

Why 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.

1

Match the queryKey Exactly

Root cause — key typo or structural mismatch
2 min

Compare your useQuery key and your invalidateQueries key character by character. They must be identical arrays.

Common key mismatches
// ❌ 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.

2

Call invalidateQueries in onSuccess

Mutation succeeds but list doesn't update
3 min

Always trigger cache invalidation inside onSuccess of useMutation . This guarantees the invalidation only happens after the server confirms success.

Complete useMutation + invalidation pattern
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)
    },
  })
}
3

Use Partial Key Matching to Invalidate Related Queries

Invalidate multiple related queries at once
3 min

Passing 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.

Partial key matching — invalidate a family of queries
// 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"] })
}
4

Use setQueryData for Instant Optimistic Updates

UI lag after mutation — want instant feedback
5 min

Instead of waiting for a refetch, update the cache directly with setQueryData for instant UI response. Roll back with the snapshot if the mutation fails.

Optimistic update — complete pattern
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] })
    },
  })
}
5

Await invalidateQueries to Prevent Race Conditions

Query updates before mutation response arrives
2 min

If 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.

Await invalidation in onSuccess
// ❌ 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

Frequently Asked Questions

Why does invalidateQueries not trigger a refetch?+
The most common cause is a queryKey mismatch — the key passed to invalidateQueries does not match the queryKey used in useQuery. TanStack Query uses deep equality to match keys, so ['posts', { userId }] and ['posts', userId] are different keys even if the values look the same.
Where should I call invalidateQueries after a mutation?+
Call invalidateQueries inside the onSuccess callback of useMutation. This ensures it only runs after the mutation succeeds — not on error or loading. You can also use onSettled to invalidate regardless of success or failure, which is safer for ensuring UI consistency.
What is the difference between invalidateQueries and refetchQueries?+
invalidateQueries marks matching queries as stale so they will refetch the next time they have active subscribers. refetchQueries immediately triggers a refetch regardless of staleTime. Use invalidateQueries for most mutations — it is more efficient because it only refetches if the query is currently in use.
How do I invalidate all queries for a feature at once?+
Use partial key matching — pass just the first segment of your queryKey array. For example, invalidateQueries({ queryKey: ['posts'] }) will invalidate ['posts'], ['posts', 1], ['posts', { status: 'published' }], and any other key starting with 'posts'.
What is an optimistic update in TanStack Query?+
An optimistic update uses setQueryData to immediately update the cache with the expected result before the mutation completes. If the mutation fails, you roll back the cache to the previous value using the context returned from onMutate. This makes the UI feel instant.
Should I use invalidateQueries or setQueryData after a mutation?+
Use setQueryData for instant optimistic updates when user experience is critical (editing a todo, liking a post). Use invalidateQueries to trigger a server refetch after mutations that affect data you can't predict client-side (creating a post with server-generated fields like ID and timestamps).

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