TanStack Query Integration
ORPC integrates seamlessly with TanStack Query (React Query) to provide powerful client-side data fetching with caching, automatic refetching, and optimistic updates.Setup
The TanStack Query integration is configured insrc/utils/orpc.ts:
QueryClient Configuration
Error Handling with Toasts
TheQueryCache is configured to show toast notifications on errors:
- Automatic error notifications: Users see errors immediately
- Retry action: Built-in retry button invalidates all queries
- Global error handling: No need to handle errors in every component
Creating Query Utils
ThecreateTanstackQueryUtils function wraps your ORPC client:
Using Queries
Basic Query
UsequeryOptions() to create TanStack Query options:
src/app/todos/page.tsx:21:
Query with Authentication
Protected procedures automatically include credentials:src/app/dashboard/page.tsx:12:
Using Mutations
Basic Mutation
UsemutationOptions() to create mutation configurations:
Mutation with Refetch
Invalidate queries after mutations to refetch fresh data: Real example fromsrc/app/todos/page.tsx:22-29:
Multiple Mutations
Handle multiple related mutations efficiently: Real example fromsrc/app/todos/page.tsx:30-43:
Complete Component Example
Here’s a full example combining queries and mutations: Fromsrc/app/todos/page.tsx:
Loading States
TanStack Query provides granular loading states:Mutation States
Mutations also provide detailed state information:Cache Invalidation
Invalidate queries to trigger refetches:Type Safety
All query and mutation options are fully typed:Retry Logic
TanStack Query automatically retries failed queries. The global error handler provides a manual retry option:Best Practices
- Refetch after mutations: Always refetch related queries after successful mutations
- Use loading states: Show loading indicators during queries and mutations
- Handle errors gracefully: The global error handler catches most errors, but handle specific cases when needed
- Disable during mutations: Disable form inputs while mutations are pending
- Invalidate queries: Use
queryClient.invalidateQueries()for cache invalidation
Next Steps
- Learn about ORPC client setup
- Explore creating custom procedures
- See authentication integration