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

