Course contentsShow
← React
Lesson 609 of 2,39616. useEffect for Data FetchingFree lesson

Optimistic Updates and Mutations Made Simple

useMutation hook handles POST/PUT/DELETE with automatic cache invalidation and rollback on failure.

Optimistic Updates and Mutations Made Simple

You'll learn: How useMutation handles writes (POST/PUT/DELETE) with automatic cache updates and failure rollback.

The Pain of Manual Mutations

With raw useEffect fetching, when you POST a new item or DELETE an existing one, you face two problems:

  1. Waiting for the server – users see a loading spinner while the mutation completes
  2. Manual cache sync – after success, you must manually refetch or update your local state to show the change

This creates a laggy, janky experience.

What useMutation Does

TanStack Query's useMutation hook handles write operations (creating, updating, deleting data) and solves both problems:

const mutation = useMutation({
  mutationFn: (newTodo) => fetch('/api/todos', {
    method: 'POST',
    body: JSON.stringify(newTodo)
  }),
  onSuccess: () => {
    queryClient.invalidateQueries(['todos'])
  }
})

Call mutation.mutate(data) to trigger it. The library automatically tracks isLoading, isError, and isSuccess states.

Automatic Cache Invalidation

The onSuccess callback uses invalidateQueries to tell React Query "this data is now stale, refetch it." This happens automatically after your mutation succeeds—no manual refetch logic needed.

Optimistic Updates: The Magic Part

Want the UI to update instantly, before the server responds? Use the onMutate callback to update the cache immediately, then onError to roll back if the mutation fails:

onMutate: async (newTodo) => {
  // Cancel refetches & snapshot old data
  await queryClient.cancelQueries(['todos'])
  const previous = queryClient.getQueryData(['todos'])
  
  // Optimistically update
  queryClient.setQueryData(['todos'], old => [...old, newTodo])
  
  return { previous } // For rollback
},
onError: (err, variables, context) => {
  queryClient.setQueryData(['todos'], context.previous)
}

If the server fails, the rollback is automatic. Users see instant feedback with safety.

Key Takeaway: useMutation eliminates boilerplate for write operations by managing loading states, automatic cache invalidation on success, and even optimistic updates with rollback—all without manual effect juggling.