Blog>
Snippets

Optimistic Updates with React Query

Demonstrate performing optimistic updates in React applications, simulating immediate UI feedback on data mutations.
const { mutate } = 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: () => {
    queryClient.invalidateQueries('todos')
  },
})
This code shows how to implement optimistic updates with React Query. When a new todo item is added, the UI updates immediately before the server responds. On a successful update, the cache is invalidated to fetch the latest data. If an error occurs, the UI reverts to the previous state.
// In your component or wherever you trigger updates
const handleUpdateTodo = (newTodo) => {
  mutate(newTodo)
}
This function `handleUpdateTodo` triggers the `mutate` function with the new todo item. It's meant to be used within a React component, where you can pass the new todo item to update the UI optimistically.