Back to results for “Forms”
React › Data Fetching (React Query & SWR)

How would you handle a mutation, such as creating a new item, using React Query?

Intermediate

Answer

React Query provides a useMutation hook specifically for actions that change data on the server, like creating, updating, or deleting something. After the mutation succeeds, you can tell React Query to refresh any related cached data so the screen shows the latest information automatically.
import { useMutation, useQueryClient } from '@tanstack/react-query';

function AddProductForm() {
  const queryClient = useQueryClient();
  const mutation = useMutation({
    mutationFn: (newProduct) => fetch('/api/products', { method: 'POST', body: JSON.stringify(newProduct) }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['products'] }),
  });

  return <button onClick={() => mutation.mutate({ name: 'New Item' })}>Add Product</button>;
}
Real-world example An admin panel automatically refreshes its product list the moment a new product is successfully added, since the mutation tells React Query to invalidate and refetch the products list right after the request succeeds.

Common follow-ups: What does invalidating a query actually do behind the scenes?;How would you show a loading spinner specifically while a mutation is in progress?