Implementing Optimistic Updates

Show how to implement optimistic updates in a React application using React Query, to instantly update the UI based on a presumed successful mutation.
import { useMutation, useQueryClient } from 'react-query';

const updateTodo = async (newTodo) => {
  // Your API call here
Defines an asynchronous function `updateTodo` for updating a todo item, which will be called by the mutation.
const queryClient = useQueryClient();
Uses the useQueryClient hook to get the current query client instance for managing queries and mutations.
const mutation = useMutation(updateTodo, {
  onMutate: async (newTodo) => {
    await queryClient.cancelQueries(['todos']);
    const previousTodos = queryClient.getQueryData(['todos']);
    queryClient.setQueryData(['todos'], (old) => [...old, newTodo]);
    return { previousTodos };
  onError: (err, newTodo, context) => {
    queryClient.setQueryData(['todos'], context.previousTodos);
  onSettled: () => {
Implements an optimistic update for adding a new todo item. Before the mutation is confirmed by the server, the UI is optimistically updated as if the mutation was successful. If an error occurs, the original data is restored.