tRPC Mutations with Optimistic Updates
You'll learn how to combine tRPC's type-safe mutations with TanStack Query's optimistic update hooks for instant UI feedback.
The Big Picture
You've seen TanStack Query's optimistic updates and tRPC queries separately. Now they unite: trpc.user.create.useMutation() returns the same TanStack Query mutation interface you know, with full end-to-end type safety. This means you can use onMutate, onError, and onSettled hooks just like regular TanStack Query mutations—but with TypeScript knowing your exact input/output types from server to client.
How It Works
When you call a tRPC mutation hook, you get back the familiar mutation object:
const mutation = trpc.user.create.useMutation({
onMutate: async (newUser) => {
// Cancel outgoing queries
await utils.user.list.cancel();
// Snapshot previous value
const previousUsers = utils.user.list.getData();
// Optimistically update cache
utils.user.list.setData(undefined, (old) =>
[...(old ?? []), newUser]
);
return { previousUsers }; // Context for rollback
},
onError: (err, newUser, context) => {
// Rollback on failure
utils.user.list.setData(undefined, context?.previousUsers);
},
onSettled: () => {
// Refetch to sync with server
utils.user.list.invalidate();
}
});
The magic: TypeScript infers newUser's type from your server procedure definition. No manual typing needed. You get autocomplete and errors if you access wrong properties.
The Workflow
Think of it like ordering food with a confident waiter: they write your order down immediately (optimistic update), but if the kitchen says "we're out," they apologize and cross it off (rollback).
Key Takeaway: tRPC mutations are TanStack Query mutations with end-to-end type safety—use the same onMutate/onError/onSettled pattern, but enjoy full TypeScript inference from server procedures to client callbacks.