Principle:Langgenius Dify React Query Pattern
| Knowledge Sources | Dify |
|---|---|
| Domains | Frontend, Data Fetching, State Management |
| Last Updated | 2026-02-12 07:00 GMT |
Overview
Dify wraps its service-layer API calls in TanStack React Query hooks to provide automatic caching, request deduplication, cache invalidation, and declarative data fetching across the frontend application.
Description
Each domain module in the service layer has a corresponding use-*.ts file that exposes custom hooks built on useQuery and useMutation from TanStack React Query. These hooks define structured query keys organized by namespace (e.g., ['common', 'user-profile'], ['explore', 'appList', locale]) that enable fine-grained cache management. A shared useInvalid utility provides a reusable function for invalidating query groups by key prefix after mutations succeed.
The pattern separates queries (read operations) from mutations (write operations) following React Query conventions. Queries use useQuery with typed query functions that call the underlying service functions, while mutations use useMutation with onSuccess callbacks that invalidate related query caches. This ensures that after a user creates, updates, or deletes a resource, related list and detail queries automatically refetch fresh data without manual state synchronization.
Query key factories (e.g., commonQueryKeys.modelList(type), commonQueryKeys.filePreview(fileID)) enable parameterized cache entries and allow selective invalidation. The consistent use of as const assertions on query key arrays provides TypeScript-level type safety for cache operations, preventing accidental key mismatches.
Usage
Use this principle when:
- Adding new data-fetching hooks for any service module in the frontend
- Implementing optimistic updates or cache invalidation after mutation operations
- Designing query key hierarchies for new domain areas that need selective cache management
Theoretical Basis
This pattern implements the Stale-While-Revalidate caching strategy, where cached data is served immediately while fresh data is fetched in the background. Combined with the Command Query Responsibility Segregation (CQRS) idea of separating reads from writes, this approach reduces redundant network requests, eliminates manual loading state management, and ensures UI consistency across components that share the same data.