React Query - `useMutation` Tutorial 🎯

beginner
11 min

React Query - useMutation Tutorial 🎯

Welcome to our comprehensive guide on React Query's useMutation! This tutorial is designed to cater to both beginners and intermediate learners, so let's dive in!

Introduction 📝

useMutation is a React Query hook that allows you to perform mutations (changes) on your data. It's a powerful tool for managing side-effects in your React applications.

Why use useMutation?

  1. Simplifies Mutations: useMutation handles the logic for sending requests, handling errors, and updating the state for you.
  2. Automatic Optimistic Updates: It allows for optimistic UI updates before the mutation is confirmed.
  3. Integration with Query: It seamlessly integrates with other React Query hooks like useQuery for a cohesive data management solution.

Getting Started 💡

Before we dive into the useMutation hook, ensure you have React and React Query installed in your project. If not, you can install them using npm or yarn:

bash
npm install react react-query

or

bash
yarn add react react-query

Importing useMutation

jsx
import { useMutation } from 'react-query';

Basic Usage 📝

Let's create a simple mutation to create a new post in a mock API.

jsx
const createPostMutation = async (title) => { const response = await fetch('https://api.example.com/posts', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ title }), }); const data = await response.json(); return data; }; // Use the mutation in a functional component const PostForm = () => { const [createPost, { isLoading, error }] = useMutation(createPostMutation); const handleSubmit = (e) => { e.preventDefault(); const title = e.target.title.value; createPost(title); }; return ( <form onSubmit={handleSubmit}> <input type="text" name="title" placeholder="Enter post title" /> <button type="submit" disabled={isLoading}> {isLoading ? 'Saving...' : 'Save Post'} </button> {error && <div>Error: {error.message}</div>} </form> ); };

In the example above, useMutation takes a function (createPostMutation) as an argument and returns an array with two elements:

  1. The createPost function that you call to execute the mutation.
  2. An object containing the mutation's status (isLoading) and any errors that occurred.
Quick Quiz
Question 1 of 1

What does `useMutation` return in the example above?

Advanced Usage 💡

useMutation offers several options for configuring your mutations. Let's explore some of them:

Configuring Options 📝

You can pass an options object to customize the behavior of your mutation.

jsx
const [createPost, { isLoading, error }] = useMutation(createPostMutation, { onSuccess: (data) => console.log(`Post created: ${data.id}`), onError: (error) => console.error(`Error creating post: ${error.message}`), });

Here, we've added an onSuccess and onError callback for logging success and error messages, respectively.

Optimistic UI 💡

React Query's optimistic UI allows you to update the UI before the mutation is confirmed.

jsx
const [createPost, { isLoading, error }] = useMutation(createPostMutation, { onMutate: (title) => { const prevPosts = queryClient.getQueryData('posts'); queryClient.setQueryData('posts', (oldPosts) => [ ...oldPosts, { id: crypto.randomUUID(), title }, ]); }, onError: (error, variables, context) => { queryClient.setQueryData('posts', (oldPosts) => oldPosts.filter((post) => post.id !== context.mutationId)); }, });

In this example, we've added an onMutate callback that optimistically adds the new post to the list before the mutation is executed, and an onError callback that removes the post from the list if the mutation fails.

Conclusion ✅

With this tutorial, you've learned the basics of using the useMutation hook in your React applications. Happy coding! 🚀

Remember to check back on CodeYourCraft for more in-depth tutorials and resources to help you master React Query! 📝

Quick Quiz
Question 1 of 1

What is the primary purpose of the `useMutation` hook in React Query?