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.
Optimistic Updates with tRPC Mutations is a free tRPC End-to-End Type Safe APIs lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the tRPC End-to-End Type Safe APIs learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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' });Getting the Query Utils
To touch the cache you need the tRPC utils object. It exposes per-query cancel, get, and set methods that mirror React Query.
const utils = trpc.useUtils();Cancel In-Flight Queries
Inside onMutate, first cancel any outgoing refetches so they do not overwrite your optimistic value.
onMutate: async (newTodo) => {
await utils.todo.list.cancel();
}Snapshot the Previous Value
Save the current cache so you can roll back if the mutation fails.
const previous = utils.todo.list.getData();Apply the Optimistic Change
Write the expected new state into the cache with setData. The UI updates instantly.
utils.todo.list.setData(undefined, (old) =>
old ? [...old, { id: 'temp', text: newTodo.text }] : old
);Return a Rollback Context
Return the snapshot from onMutate. React Query passes it to onError as context.
return { previous };Roll Back on Error
If the server rejects the mutation, restore the snapshot so the UI matches reality.
onError: (err, newTodo, context) => {
utils.todo.list.setData(undefined, context?.previous);
}Reconcile on Settled
Whether it succeeds or fails, invalidate the query in onSettled so the cache resyncs with the server truth.
onSettled: () => {
utils.todo.list.invalidate();
}Putting It Together
The full optimistic mutation wires every callback in one place.
const add = trpc.todo.add.useMutation({
onMutate: async (n) => {
await utils.todo.list.cancel();
const previous = utils.todo.list.getData();
utils.todo.list.setData(undefined, (o) => o ? [...o, { id: 'temp', text: n.text }] : o);
return { previous };
},
onError: (e, n, ctx) => utils.todo.list.setData(undefined, ctx?.previous),
onSettled: () => utils.todo.list.invalidate(),
});Best Practices
Keep optimistic updates safe:
- Always cancel in-flight queries first
- Always snapshot before mutating
- Use a temporary id you can replace later
- Invalidate on settle to avoid drift
Quick Check
Test your optimistic update knowledge.
Recap
You implemented optimistic updates with tRPC and React Query:
- Cancel queries, snapshot, then setData in
onMutate - Restore the snapshot in
onError - Invalidate in
onSettled
Your UI now feels instant while staying consistent with the server.
Frequently asked questions
Is the “Optimistic Updates with tRPC Mutations” lesson free?
Yes — the full text of “Optimistic Updates with tRPC Mutations” is free to read here on the web, and the tRPC End-to-End Type Safe APIs course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the tRPC End-to-End Type Safe APIs course, upgrade to CoddyKit PRO.
What will I learn in “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. You practise tRPC End-to-End Type Safe APIs with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start tRPC End-to-End Type Safe APIs?
No prior experience is required. tRPC End-to-End Type Safe APIs on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Optimistic Updates with tRPC Mutations” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this tRPC End-to-End Type Safe APIs lesson?
Yes. Every tRPC End-to-End Type Safe APIs lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
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