Queries, Mutations, and Subscriptions
Use tRPC's typed queries and mutations from React components with full autocomplete and error types.
Queries, Mutations, and Subscriptions is a free React Academy lesson on CoddyKit — lesson 3 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 React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Defining a Query Procedure
Chain .input(zodSchema).query(async ({ input, ctx }) => ...) onto publicProcedure. The handler receives the validated input and the request context. Return any serializable value: an object, array, or primitive.
The return type is automatically inferred and becomes the data type of the corresponding useQuery hook on the client.
Calling a Query from React
trpc.post.getById.useQuery({ id: '1' }) calls the getById procedure in the post router. The hook returns the familiar React Query result object: { data, isLoading, isError, refetch }.
The input object is statically typed: passing { id: 123 } when the schema expects a string is a TypeScript error caught at development time.
Defining a Mutation Procedure
Use .input(zodSchema).mutation(async ({ input, ctx }) => ...) for server-side write operations: creating, updating, or deleting data. Mutations are called explicitly rather than running on mount.
The mutation handler has access to the full request context (including session from NextAuth) via ctx.
Calling a Mutation from React
const { mutate, isLoading, error } = trpc.post.create.useMutation(). Call mutate({ title: 'New', content: '...' }) to trigger the mutation. Like React Query's useMutation, it does not run on mount.
Pass onSuccess and onError callbacks to the useMutation options for post-mutation side effects.
Invalidating Cache After Mutation
To refresh query data after a successful mutation, use the tRPC utilities hook: const utils = trpc.useUtils(). In onSuccess, call utils.post.getAll.invalidate() to trigger a refetch of the post list.
This is the tRPC equivalent of React Query's queryClient.invalidateQueries() and follows the same stale-and-refetch pattern.
Input Validation with Zod
tRPC uses Zod for input validation by default. The Zod schema runs on the server at runtime, rejecting malformed input before it reaches your handler. The same schema provides TypeScript types for the client.
This dual role (runtime validation + TypeScript types) eliminates duplication: you define the contract once in Zod and get both safety guarantees for free.
Request Batching with httpBatchLink
By default, tRPC uses httpBatchLink which batches multiple concurrent tRPC requests into a single HTTP request. Multiple useQuery calls in the same component render cycle are sent together and resolved together.
This reduces network overhead significantly compared to individual HTTP requests for each query in a page with multiple data requirements.
tRPC Subscriptions Overview
Define a subscription procedure: publicProcedure.subscription(async function*() { while (true) { yield await nextEvent(); } }). Subscriptions use async generators and require a WebSocket transport.
Subscriptions are ideal for real-time features: live notifications, collaborative editing cursors, or streaming AI responses.
WebSocket Transport Setup
Replace httpBatchLink with a combination of httpBatchLink and wsLink using splitLink: route subscriptions to wsLink and queries/mutations to httpBatchLink. Create the WebSocket client with createWSClient({ url: 'ws://localhost:3000' }).
This hybrid transport means most requests use efficient HTTP batching while subscriptions use persistent WebSocket connections.
Calling Subscriptions from React
trpc.notifications.onNew.useSubscription(undefined, { onData: (notification) => addToList(notification), onError: console.error }) subscribes to the procedure. The onData callback is called for each yielded value.
The subscription is automatically re-established if the WebSocket disconnects and reconnects.
Combining Queries, Mutations, and Subscriptions
A real-time list page might use a query to load the initial list, a mutation to add an item, and a subscription to receive live additions from other users. All three are typed against the same AppRouter and compose naturally.
The cache invalidation strategy depends on whether you prefer full refetch (invalidate after mutation) or cache updates (utils.post.getAll.setData).
tRPC Mutation and Cache Invalidation
Which tRPC utility method triggers a refetch of a query after a mutation succeeds?
Lesson Recap
Define queries with .query() and mutations with .mutation(), both validated by Zod schemas. On the client, use trpc.router.procedure.useQuery() and useMutation(). Invalidate queries post-mutation with utils.procedure.invalidate(). Subscriptions use async generators and require wsLink for WebSocket transport.
httpBatchLink batches concurrent queries into a single HTTP request by default.
Frequently asked questions
Is the “Queries, Mutations, and Subscriptions” lesson free?
Yes — the full text of “Queries, Mutations, and Subscriptions” is free to read here on the web, and the React Academy 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 React Academy course, upgrade to CoddyKit PRO.
What will I learn in “Queries, Mutations, and Subscriptions”?
Use tRPC's typed queries and mutations from React components with full autocomplete and error types. You practise React Academy 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 React Academy?
No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Queries, Mutations, and Subscriptions” 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 React Academy lesson?
Yes. Every React Academy 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
- The Problem tRPC Solves
- Setting Up tRPC with React and Next.js
- Queries, Mutations, and Subscriptions
- Integrating tRPC with React Query and Auth