What Distinguishes Queries from Mutations
You'll learn: The fundamental conceptual and practical differences between queries (read operations) and mutations (write operations) in tRPC.
The Conceptual Foundation
In tRPC, queries are procedures that fetch data without changing server state, while mutations are procedures that modify server state. Think of queries like looking at a menu in a restaurant—you're just reading information. Mutations are like placing an order—you're making something happen that changes the restaurant's state (kitchen starts cooking, your bill increases).
This distinction isn't just philosophical. It affects how tRPC handles these operations under the hood, how clients cache responses, and how you structure your API.
Why the Distinction Matters
Queries are safe to call multiple times. Calling getUser five times doesn't create five users—it just retrieves the same data five times. This makes queries:
- Cacheable by default
- Safe to retry automatically on failure
- Callable on component mount without side effects
Mutations have consequences. Calling createUser five times creates five users. This makes mutations:
- Not cached by default (you want fresh data after changes)
- Require explicit invocation (user clicks a button)
- Need careful error handling (failed mutations may need rollback)
Practical Implications
When building with tRPC, you choose .query() for operations that don't modify data: fetching lists, getting details, searching. You choose .mutation() for operations that do modify data: creating, updating, deleting, or triggering actions.
This separation helps both the framework and future maintainers understand intent at a glance.
Key Takeaway: Queries read without side effects and are safe to cache and retry; mutations write with side effects and require explicit invocation—this distinction shapes how tRPC handles each operation differently.