Optimistic Patterns with React Query and Zustand
Use React Query's onMutate/onError/onSettled callbacks and Zustand for structured optimistic UI workflows.
React Query useMutation Overview
React Query's useMutation hook provides built-in infrastructure for optimistic updates through three lifecycle callbacks: onMutate (fires before the mutation, return a context object), onError (fires on failure, receives the context), and onSettled (fires on success or failure). This structure is designed specifically for optimistic patterns.
onMutate: The Optimistic Update Phase
In onMutate, you perform three steps: first, cancel any in-flight queries for the affected data (await queryClient.cancelQueries({ queryKey })), then snapshot the current cache (queryClient.getQueryData(queryKey)), and finally apply the optimistic update to the cache (queryClient.setQueryData(queryKey, updater)). Return the snapshot as context.
All lessons in this course
- What Is Optimistic UI and When to Use It
- Implementing Optimistic Updates Manually
- Rollback on Error and Conflict Resolution
- Optimistic Patterns with React Query and Zustand