Blog>
Snippets

Implementing Optimistic Updates with React Query

Showcase how to perform optimistic updates in React Query by predicting server-side changes on the client side before the mutation request completes to enhance user experience.
import { useMutation, useQueryClient } from 'react-query';

const addSection = async (newSection) => {
  // Replace this with the real request to your backend
  return fetch('/api/addSection', {
    method: 'POST',
    body: JSON.stringify(newSection),
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(res => res.json());
};
This code defines an asynchronous function addSection that simulates sending a section data to a server. It's intended to be replaced with an actual request to your backend API.
const { mutate } = useMutation(addSection, {
  onMutate: async (newSection) => {
    const queryClient = useQueryClient();
    await queryClient.cancelQueries('sections');
    const previousSections = queryClient.getQueryData('sections');
    queryClient.setQueryData('sections', old => [...old, newSection]);
    return { previousSections };
  },
  onError: (error, newSection, context) => {
    queryClient.setQueryData('sections', context.previousSections);
  },
  onSettled: () => {
    queryClient.invalidateQueries('sections');
  },
});
This code utilizes the `useMutation` hook from React Query to trigger the addSection function. It implements optimistic updates by temporarily adding the new section to the local cache before the server has responded. If the mutation fails, the local cache is rolled back to its previous state. The `onSettled` callback ensures the data is refetched from the server, keeping the client and server in sync.