Course contentsShow
← Web Development
Lesson 1560 of 2,98228. GraphQL FundamentalsFree lesson

useMutation Hook

Execute mutations with useMutation, handle loading states, and access returned data after mutation completes.

useMutation Hook

You'll learn how to execute GraphQL mutations with Apollo Client's useMutation hook, manage loading states during the operation, and work with the data returned after the mutation completes.

What is useMutation?

Just like useQuery helps you fetch data, useMutation is Apollo Client's React hook for modifying data on your GraphQL server. Think of it like submitting a form—you trigger the action when you're ready (not automatically), you want to show a loading spinner while it processes, and you need to handle the response once it comes back.

How It Works

Unlike useQuery which runs automatically on component mount, useMutation returns a function that you call when you're ready to execute the mutation:

import { useMutation, gql } from '@apollo/client';

const CREATE_POST = gql`
  mutation CreatePost($title: String!, $content: String!) {
    createPost(title: $title, content: $content) {
      id
      title
    }
  }
`;

function NewPostForm() {
  const [createPost, { data, loading, error }] = useMutation(CREATE_POST);

  const handleSubmit = (event) => {
    event.preventDefault();
    createPost({ 
      variables: { 
        title: 'My Post', 
        content: 'Hello world' 
      } 
    });
  };

  if (loading) return <p>Saving...</p>;
  if (error) return <p>Error: {error.message}</p>;
  if (data) return <p>Post created: {data.createPost.title}</p>;

  return <button onClick={handleSubmit}>Create Post</button>;
}

The hook returns an array: the mutation function to call, and an object containing data, loading, and error states that update as the mutation progresses.

Key Takeaway: useMutation gives you a function to trigger mutations on demand, plus reactive state variables (loading, error, data) to handle the complete lifecycle of your data modification operations.