Capítulo 28 de 80

Chapter 28: Invalidations from Mutations

Core Idea

The idiomatic place to call invalidateQueries is a mutation's onSuccess callback — returning a Promise from it (e.g. via await/Promise.all) keeps the mutation's isPending true until the invalidation/refetch is actually complete, not just the write.

Key Concepts

  • The pattern: when a mutation succeeds, the queries whose data it affects are "very likely" stale — invalidate them from onSuccess rather than leaving it to chance/staleTime.
  • Multiple affected query groups: Promise.all([queryClient.invalidateQueries({queryKey: ['todos']}), queryClient.invalidateQueries({queryKey: ['reminders']})]) invalidates several unrelated key groups from one mutation.
  • Await matters: returning (and thus awaiting) the invalidation promise from onSuccess means mutation.isPending stays true until the refetch resolves too — useful when the UI shouldn't consider the operation "done" until fresh data has actually landed.
  • Not limited to onSuccess: the same queryClient invalidation calls can be wired into any of useMutation's other lifecycle callbacks (onSettled, etc.), not just onSuccess.

Code Examples

const queryClient = useQueryClient()

const mutation = useMutation({
  mutationFn: addTodo,
  onSuccess: async () => {
    await Promise.all([
      queryClient.invalidateQueries({ queryKey: ['todos'] }),
      queryClient.invalidateQueries({ queryKey: ['reminders'] }),
    ])
  },
})
  • What it demonstrates: invalidating two unrelated key groups after one mutation succeeds, with isPending correctly reflecting that the refetch is still in flight.

Key Takeaways

  1. onSuccess on the mutation itself (not on the caller's mutate() call) is the standard place for invalidation logic that should always run.
  2. Return/await the invalidation promise when the UI's "done" state should wait for fresh data, not just the write acknowledgment.
  3. One mutation can legitimately invalidate several unrelated query groups — don't assume a 1:1 mapping between a mutation and a single query key.

Connects To

  • Query Invalidation: the underlying mechanism and matching rules used here.
  • Mutations: the full callback lifecycle this pattern is one instance of.