TanStack Query mutations, invalidation, and optimistic UI
Queries read server state.
Mutations change server state.
query
β read remote state
mutation
β request remote change
The hard part is not sending the request. It is reconciling the client cache with the authoritative server afterward.
Basic mutationβ
import { useMutation, useQueryClient } from '@tanstack/react-query'
async function createProduct(input: NewProduct): Promise<Product> {
const response = await fetch('/api/products', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(input),
})
if (!response.ok) {
throw new Error('Could not create product')
}
return response.json()
}
function NewProductButton() {
const queryClient = useQueryClient()
const mutation = useMutation({
mutationFn: createProduct,
onSuccess: async () => {
await queryClient.invalidateQueries({
queryKey: ['products'],
})
},
})
return (
<button
disabled={mutation.isPending}
onClick={() => mutation.mutate({ name: 'Lamp', price: 20 })}
>
{mutation.isPending ? 'Savingβ¦' : 'Create'}
</button>
)
}
Mutation lifecycleβ
mutate(variables)
β
βΌ
pending
β
βββ success
β βββ update cache OR invalidate
β βββ continue UI flow
β
βββ error
βββ show/recover/rollback
A mutation result is not automatically the same thing as every cached query that may be affected by the change.
Invalidationβ
When a mutation makes related cached data out of date, invalidate the relevant queries.
await queryClient.invalidateQueries({
queryKey: ['products'],
})
Conceptually:
mutation succeeds
β
βΌ
related cache is known stale
β
βΌ
invalidate matching queries
β
βΌ
active observers may refetch
Target invalidation deliberately. Invalidating the entire cache after every mutation destroys much of the value of caching.
Prefix matchingβ
If your query keys are hierarchical:
['products']
['products', 'list', filters]
['products', 'detail', id]
then invalidating a broad prefix may affect several related entries.
Use key factories and naming conventions so this behavior is intentional.
Direct cache updateβ
If the mutation response returns the authoritative updated entity, you can write it directly into a cache entry.
onSuccess: (product) => {
queryClient.setQueryData(
['product', product.id],
product,
)
}
This can avoid an extra request for that exact resource.
But consider whether related list/filter caches also became stale.
Invalidate vs direct updateβ
Direct cache update
βββ immediate
βββ precise
βββ requires correct cache-shape knowledge
Invalidation + refetch
βββ simpler
βββ trusts server reconstruction
βββ requires another request for active data
A production application may combine both.
Optimistic UI: UI-only approachβ
TanStack Query v5 supports showing optimistic UI using mutation variables without necessarily editing the cache.
const addTodo = useMutation({
mutationFn: createTodo,
onSettled: async () => {
await queryClient.invalidateQueries({ queryKey: ['todos'] })
},
})
While pending, render addTodo.variables as a temporary row.
existing cached todos
+
pending mutation variables
β
optimistic visible row
This is often simpler when only one UI location needs the optimistic result.
Optimistic cache updateβ
When several parts of the UI need to observe the optimistic result, update the cache.
const mutation = useMutation({
mutationFn: updateTodo,
onMutate: async (updatedTodo) => {
await queryClient.cancelQueries({
queryKey: ['todos'],
})
const previousTodos = queryClient.getQueryData<Todo[]>(['todos'])
queryClient.setQueryData<Todo[]>(['todos'], (current = []) =>
current.map((todo) =>
todo.id === updatedTodo.id
? { ...todo, ...updatedTodo }
: todo,
),
)
return { previousTodos }
},
onError: (_error, _variables, context) => {
if (context?.previousTodos) {
queryClient.setQueryData(['todos'], context.previousTodos)
}
},
onSettled: async () => {
await queryClient.invalidateQueries({ queryKey: ['todos'] })
},
})
Optimistic rollback modelβ
snapshot previous cache
β
βΌ
apply optimistic change
β
βΌ
send mutation
βββββ΄βββββ
βΌ βΌ
success failure
β β
βΌ βΌ
reconcile restore snapshot
\ /
βΌ βΌ
invalidate/refetch if needed
Optimistic state is provisional.
The server remains authoritative.
Avoid race-condition bugsβ
Before patching a query optimistically, cancelling relevant in-flight refetches can prevent an older response from overwriting the optimistic cache.
That is why many optimistic-update examples call cancelQueries in onMutate.
Mutation errorsβ
Do not reduce every failure to one generic toast.
Separate categories where useful:
- validation error;
- authentication failure;
- authorization failure;
- conflict/version error;
- transient network failure;
- server failure.
The client should not invent success when the authoritative server rejected the change.
Server validation still winsβ
Client validation improves UX, but mutation input is untrusted on the server.
form validation passes
β
βΌ
mutation sent
β
βΌ
server validates again
β
βΌ
authorize + persist
TanStack Query does not replace backend validation or authorization.
Idempotencyβ
For actions that must not be duplicatedβpayments, booking confirmation, order creationβdesign server-side idempotency.
Disabling a button on the client is not a complete duplicate-submission guarantee.
Mutation state vs form stateβ
Keep responsibilities separate:
React Hook Form
βββ input values
βββ field validation
βββ dirty/touched
βββ submit preparation
TanStack Query mutation
βββ remote request
βββ pending/error/success
βββ cache reconciliation
βββ invalidation
These tools complement each other.
Common mistakesβ
Updating every cache manuallyβ
Direct cache writes are powerful but increase coupling to cache shapes.
Use invalidation when correctness and simplicity are more valuable than avoiding one request.
Optimistic UI without rollback/reconciliationβ
If the server can reject the mutation, provisional UI needs a recovery path.
Invalidating unrelated resourcesβ
Broad invalidation can create unnecessary network traffic.
Copying mutation result into global client stateβ
If the data remains server-owned, keep its lifecycle in the server-state cache.
Exerciseβ
Build a todo mutation flow that:
- creates a todo;
- displays pending UI;
- invalidates the list after success;
- adds an optimistic row;
- handles server failure visibly;
- explains whether the optimistic state lives in UI or cache.
Interview questionsβ
Mid-level: What is the difference between a query and a mutation?
Senior: When would you invalidate versus directly update cached data?
Senior: Why might you cancel queries before an optimistic cache update?
Staff: How would you design optimistic updates for a collaborative system where the server may reject writes because of version conflicts?