React Query is a popular library for fetching, caching, and updating asynchronous data in React applications. It provides a number of hooks, including useMutation
that allows you to perform mutations (i.e., update data) on a server and automatically update your UI with the results.
Example
In order to use the useMutation
hook, you first need to install React Query and add it to your React project. You can do this with the following command:
$ npm i @tanstack/react-query
# or
$ pnpm add @tanstack/react-query
# or
$ yarn add @tanstack/react-query
Once you have React Query installed, you can import the useMutation
hook from the @tanstack/react-query
package and use it in your functional component.
Here’s an example of how you might use useMutation
to add a new post:
import React from "react";
import ReactDOM from "react-dom/client";
import {
QueryClient,
QueryClientProvider,
useMutation
} from "@tanstack/react-query";
const queryClient = new QueryClient();
function App() {
return (
<QueryClientProvider client={queryClient}>
<AddPostComponent />
</QueryClientProvider>
);
}
function AddPostComponent() {
const { mutate, isLoading, error } = useMutation(
(post) =>
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
body: JSON.stringify(post),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
}),
{
onSuccess: async (data) => {
alert("Post added successfully: " + JSON.stringify(await data.json()));
},
onError: (error) => {
console.log(error);
}
}
);
return (
<div>
{isLoading ? (
<div>Adding Post...</div>
) : (
<button
onClick={() =>
mutate({
title: "foo",
body: "bar",
userId: 1
})
}
>
Add Post
</button>
)}
{error && <div>An error occurred: {error.message}</div>}
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.createRoot(rootElement).render(<App />);
In this example, the useMutation
hook is called with a function that performs the mutation (i.e., sends a POST
request to the /posts
endpoint) and an object with an onSuccess
callback that shows an alert with the new data (at this point you can update the UI).
The hook call returns an object, some of the object properties we can extract them as the following:
const { mutate, isLoading, error } = useMutation....
mutate function is a function that you can call to perform the mutation.
isLoading and error are properties that include information about the current state of the mutation (e.g., whether it is loading, if there was an error, etc.).
When the component renders, the useMutation
hook will return a function that you can call to add a new post. When the user clicks the “Add post” button, the mutate
function will be called with the new post data, and React Query will automatically handle sending the request to the server, updating the cache with the latest data, and calling the onSuccess
callback to update the UI.
In a summary React Query useMutation
hook is a powerful tool for managing asynchronous data in your React applications. It makes it easy to perform mutations and automatically update your UI with the results, without having to worry about managing the details of fetching, caching, and updating data.