liveBook · Manning

useMutation

As explained in React Hooks in Action: With Suspense and Concurrent Mode

useMutation is a React Query hook that coordinates an operation for changing server-side data and exposes its execution state.

useMutation coordinates a server-side change from a React component. A form calls its returned mutate function, while React Query exposes loading, error, status, and returned data for the operation. section 10.3.5

Use the hook in three steps:

  • Pass an asynchronous function that sends the new or updated data to the server. section 10.3.5
  • Destructure mutate and status properties, optionally renaming mutate for the component action. section 10.3.5
  • Call mutate with the form data; React Query runs the asynchronous function and updates the mutation state. section 10.3.5
  • Configure onSuccess to update the query cache after the server accepts the change, then navigate or refresh the relevant UI. section 10.3.5

Saving a new bookable

const {mutate: createBookable, status, error} = useMutation(\n item => createItem("http://localhost:3001/bookables", item),\n {\n onSuccess: bookable => {\n queryClient.setQueryData(\n "bookables",\n old => [...(old || []), bookable]\n );\n navigate(`/bookables/${bookable.id}`);\n }\n }\n);\n\n// Submit handler\ncreateBookable(newBookableFields); section 10.3.5

Listing 10.14 BookableNew saving data to the server with useMutation
import {useNavigate} from "react-router-dom";
import {useQueryClient, useMutation} from "react-query";             #1
 
import useFormState from "./useFormState";
import {createItem} from "../../utils/api";                          #2
 
import BookableForm from "./BookableForm";
import PageSpinner from "../UI/PageSpinner";
 
export default function BookableNew () {
  const navigate = useNavigate();
  const formState = useFormState();
  const queryClient = useQueryClient();
 
  const {mutate: createBookable, status, error} = useMutation(       #3
 
    item => createItem("http://localhost:3001/bookables", item),     #4
 
    {
      onSuccess: bookable => {                                       #5
        queryClient.setQueryData(                                    #6
          "bookables",
          old => [...(old || []), bookable]
        );
 
        navigate(`/bookables/${bookable.id}`);                       #7
      }
    }
  );
 
  function handleSubmit() {
    createBookable(formState.state);                                 #8
  }
 
  if (status === "error") {
    return <p>{error.message}</p>
  }
 
  if (status === "loading") {
    return <PageSpinner/>
  }
 
  return (
    <BookableForm
      formState={formState}
      handleSubmit={handleSubmit}
    />
  );
}
#1 Import React Query hooks.
#2 Import the createItem API function.
#3 Call useMutation, assigning the mutation function to the createBookable variable.
#4 Pass useMutation an asynchronous function.
#5 Set an onSuccess callback.
#6 Add the new bookable to the “bookables” query cache.
#7 Navigate to the newly created bookable.
#8 Call the createBookable mutation function with the fields for the new bookable.

The complete listing shows how useMutation connects a form, API request, query client, success callback, cache update, and navigation. section 10.3.5

How React Hooks in Action: With Suspense and Concurrent Mode covers it

How deep it goes
Explains mutation functions, execution status, success callbacks, cache updates, and navigation, but leaves edit and delete implementations as challenges.
Examples
Demonstrates creating a bookable, appending it to the bookables cache, navigating to it, and extending the pattern to edit and delete actions.
What it assumes
Assumes React components, asynchronous API helpers, forms, and query-client access; connects naturally with prior useQuery and caching work.
What you can do after
Apply it via React Query to build form-driven server updates and reflect successful changes in cached data and navigation.
How it connects
Connects useMutation with useQuery, the query cache, React forms, server state, and navigation.

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 Hooks in Action: With Suspense and Concurrent Mode. The section links point to the parts of the book it draws on.