Sonamu + TanStack Query Overview
Auto-generated
useUser, usePost Hooks No code writing needed
Type Safe
Service types preserved Complete type chain
Auto Caching
Memory cache Duplicate request removal
Auto Revalidation
Refresh on focus Periodic polling
Using TanStack Query Hooks in Sonamu
Hook Auto-generation
Sonamu auto-generates TanStack Query Hooks for each Service function. Generated Hooks (services.generated.ts):- Function name:
get{Entity}β Hook name:use{Entity} - Query Key:
["{Entity}", "{methodName}", ...params] - Types fully preserved (Subset support)
Basic Usage
useUser Hook
The most basic data fetching Hook.datais of typeUserSubsetMapping["A"] | undefined- Auto caching: Uses cache when called with same userId again
- Auto revalidation: Auto refresh on focus, reconnection
- Deduplication: Even if multiple components call simultaneously, API is called only once
Subset and Type Safety
Accurate types are returned according to Subset.Advanced Usage
Conditional Fetching
Fetch data only under certain conditions.true: Load data immediately (default)false: Donβt load data- Use cases: Login status, parameter existence, etc.
Dependent Fetching
Use previous data for the next request.Query Options Reuse
Reuse the same Query Options in multiple places.Mutation (Data Changes)
Create/Update/Delete with useMutation
Change data with TanStack QueryβsuseMutation.
Optimistic Updates
Update UI immediately without waiting for API response.- Button click β UI updates immediately (no waiting)
- API call in background
- Confirmed with server data on success
- Auto rollback on failure
Cache Management
Cache Invalidation
Invalidate cache of specific queries to reload.Direct Cache Modification
Modify cache directly without API call.Prefetching
Preload data to improve user experience.Practical Examples
Infinite Scroll
Implement infinite scroll instead of pagination.Real-time Polling
Refresh data periodically.Combining Multiple Hooks
TanStack Query Configuration
Global Configuration
DevTools
Visually check cache state during development.Performance Optimization
Optimization with Subset
Choose appropriate Subset for the situation to reduce network cost:Selective Revalidation
Prevent unnecessary revalidation:Parallel Requests
Load multiple data simultaneously:Cautions
Next Steps
How Services Work
Understanding auto-generation
Using Services
Basic Service usage
TanStack Query Docs
Learn more about TanStack Query
Subset System
Subset system