Blog>
Snippets

Basic useMutation example with optimistic update

Demonstrate how to implement a basic optimistic update in a React component using the useMutation hook from React Query for adding an item.
import { useMutation, useQueryClient } from 'react-query';
import axios from 'axios';

const useAddItem = () => {
  const queryClient = useQueryClient();

  return useMutation(
    newItem => axios.post('/items', newItem),
    {
      onMutate: async newItem => {
        await queryClient.cancelQueries('items');

        const previousItems = queryClient.getQueryData('items');

        queryClient.setQueryData('items', old => [...old, newItem]);

        return { previousItems };
      },
      onError: (err, newItem, context) => {
        queryClient.setQueryData('items', context.previousItems);
      },
      onSettled: () => {
        queryClient.invalidateQueries('items');
      }
    }
  );
};
This code defines a custom hook `useAddItem` using React Query's `useMutation` for adding an item. It demonstrates an optimistic update by immediately adding the new item to the local cache before the mutation is confirmed by the server. On mutation, it first cancels any ongoing fetches, saves the previous state, and sets the new item in the cache. If the mutation fails, it reverts to the previous state. Regardless of success or failure, it finally invalidates queries related to 'items' to ensure data is fresh.