Blog>
Snippets

Optimistic Update with useMutation Hook

Show how to implement an optimistic update in a todo list application when a user adds a new todo item using the useMutation hook.
import { useMutation, useQueryClient } from 'react-query';
import axios from 'axios';
First, import the necessary hooks from 'react-query' and 'axios' for making HTTP requests.
const useAddTodo = () => {
  const queryClient = useQueryClient();

  return useMutation(
    newTodo => axios.post('/api/todos', newTodo),
    {
      // Optimistically update to the new value
      onMutate: async newTodo => {
        await queryClient.cancelQueries('todos');

        const previousTodos = queryClient.getQueryData('todos');

        queryClient.setQueryData('todos', old => [...old, newTodo]);

        return { previousTodos };
      },
      // On failure, roll back to the previous value
      onError: (err, newTodo, context) => {
        queryClient.setQueryData('todos', context.previousTodos);
      },
      // After success or failure, refetch the todos query
      onSettled: () => {
        queryClient.invalidateQueries('todos');
      },
    }
  );
};
Defines a custom hook, useAddTodo, which uses the useMutation hook. It starts by optimistically adding the new todo to the current state, rolls back in case of error, and finally refetches the todos list on completion, success, or failure.
const { mutate } = useAddTodo();

const addTodo = () => {
  const newTodo = { title: 'Learn React Query', completed: false };
  mutate(newTodo);
};
This code shows how to use the custom hook. It defines a new todo item and then uses mutate to add it, relying on our optimistic update strategy.