`useMutation` runs an operation that changes remote data, such as creating, updating, or deleting a resource. It does not send the request for you: supply a promise-returning `mutationFn` that talks to the server. Set up a `QueryClient` and `QueryClientProvider` before using TanStack Query hooks. section 9.3 section 9.3.1
Delete a customer and invalidate affected queries
`const queryClient = useQueryClient(); const deletion = useMutation({ mutationFn: deleteCustomerById, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["customers"] }); queryClient.invalidateQueries({ queryKey: ["customer", { id }] }); } });` Call `deletion.mutate(id)` from the delete button. The list prefix covers customer-list queries; the individual key targets the deleted customer without invalidating every individual-customer query. section 9.3.2
Choose how a successful mutation updates cached data:
- Invalidate affected query keys when the mutation leaves their cached results uncertain. A later fetch can restore fresh data, but repeated mutations may cause avoidable requests. section 9.3 section 9.3.2
- Write the returned resource into the cache with `queryClient.setQueryData` when the API guarantees that only the known resource changed. This avoids a follow-up request; the callback must update the appropriate cached shape and key. section 9.4.1
Listing 9.13 Updating cache directly from a mutation
// useDoThing.js (excerpt)
function useDoThing(onSuccess) { #1
const { mutate: doThing } = useMutation({ #1
mutationFn: API.doThing, #1
onSuccess, #1
}); #1
return doThing;
}
//
// useThatThing.js (excerpt)
const onSuccess = (newThing) => #2
queryClient.setQueryData( #2
["currentThing", { id }], #2
newThing, #2
); #2
const doThing = useDoThing(onSuccess);
//
// useThisThing (excerpt)
const onSuccess = ({ name, done }) => #3
queryClient.setQueryData( #3
["things"], #3
(oldThings) => #3
oldThings.map((oldThing) => #3
oldThing.id !== id #3
? oldThing #3
: { id, name, count: done.length } #3
)
);
const doThing = useDoThing(onSuccess);
The hook accepts an `onSuccess` callback so its callers can update either a single-resource query or an entry in a list query from the mutation response. section 9.4.1

