liveBook · Manning

useMutation

As explained in React in Depth

useMutation is a TanStack Query hook that performs a server-side mutation and exposes its mutation state and operations.

`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

How React in Depth covers it

How deep it goes
Works through triggering a mutation, invalidating query keys, and writing returned data to the cache; does not detail mutation-state properties.
Examples
Uses customer deletion, a reusable add operation, and resource-specific cache updates after an increment.
What it assumes
Assumes React hooks and a configured QueryClientProvider; requires a separately defined promise-returning server function.
What you can do after
Apply it via TanStack Query to trigger server changes and keep affected queries fresh through invalidation or direct cache writes.
How it connects
Connects mutations to useQuery, query keys, QueryClient, cache invalidation, and direct cache updates.

Also explained in

Compare how 2 books explain useMutation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React in Depth. The section links point to the parts of the book it draws on.