TanStack Query Setup
Query client is configured in the root providers:src/app/providers.tsx
- Single
QueryClientinstance per app - Automatic request deduplication
- Background refetching
- Cache management
- DevTools in development
Type-Safe API Client
Hono RPC provides end-to-end type safety from backend to frontend:src/lib/api/client.ts
- Backend defines routes with Hono
- Types exported as
AppType - Frontend imports
AppType - Full autocomplete and type checking
Basic Usage
Simple Query
Real example from the codebase:src/components/api-status.tsx
queryKey: Unique identifier for the queryqueryFn: Function that fetches the datarefetchInterval: Background refetch interval- States:
isLoading,isError,data
Query with Parameters
Mutations
Mutations handle data modifications (POST, PUT, DELETE):mutationFn- Function that performs the mutationonSuccess- Called when mutation succeedsonError- Called when mutation failsonSettled- Called when mutation completes (success or error)
Advanced Patterns
Optimistic Updates
Update UI immediately before server response:Parallel Queries
Fetch multiple queries simultaneously:Dependent Queries
Queries that depend on previous query results:Infinite Queries
Pagination with infinite scroll:Query Invalidation
Refresh stale data after mutations:- Specific Query
- Query Prefix
- Multiple Queries
- All Queries
Error Handling
Global Error Handling
src/app/providers.tsx
Component-Level Error Handling
DevTools
TanStack Query DevTools are enabled in development:src/components/devtools.tsx
- Click the TanStack Query icon in the bottom corner
- Inspect queries, mutations, and cache
- Manually trigger refetches
- View query timelines
Best Practices
Use Descriptive Query Keys
Use Descriptive Query Keys
Query keys should be hierarchical and descriptive:
Colocate Query Logic
Colocate Query Logic
Create custom hooks for reusable queries:
Leverage Stale Time
Leverage Stale Time
Set appropriate
staleTime to reduce unnecessary refetches:Handle Loading States Gracefully
Handle Loading States Gracefully
Provide meaningful loading states:
Type Safety Examples
Fully Typed Request/Response
Type-Safe Query Parameters
Next Steps
Components
Learn about UI components and patterns
Styling
Master Tailwind CSS configuration