Optimistic Updates with tRPC Mutations
Make your Next.js UI feel instant by applying optimistic updates to tRPC mutations and rolling back cleanly when a request fails.
Why Optimistic Updates
When a user clicks a button, waiting for the server feels slow. Optimistic updates update the UI immediately, assuming the mutation will succeed, then reconcile with the real server response.
tRPC pairs perfectly with React Query, which handles the cache mechanics for you.
Anatomy of a tRPC Mutation
A mutation hook gives you mutate, isPending, and lifecycle callbacks: onMutate, onError, onSettled.
Optimistic logic lives in these callbacks.
const mutation = trpc.todo.add.useMutation();
mutation.mutate({ text: 'Buy milk' });All lessons in this course
- tRPC with Next.js App Router
- Advanced React Query Integration
- Server Components and tRPC Data Fetching
- Optimistic Updates with tRPC Mutations