Query Key Factory in Data Layer
In the Hybr1d frontend repository, we use a Query Key Factory approach to manage cache keys in our
data layer effectively. This method is integral when working with tanstack-query for queries and
mutations.
Importance of Query Key Management
Proper management of query keys is crucial for:
- Effective Caching: Allows
tanstack-queryto cache and invalidate data efficiently. - Data Consistency: Ensures data consistency across the application.
- Optimized Performance: Reduces unnecessary API calls, optimizing application performance.
Structure of Query Key Factory
A Query Key Factory is a set of functions or constants that generate query keys. These keys are used
by tanstack-query hooks to identify and manage cached data.
Example of a Query Key Factory
For the inventory data layer, the Query Key Factory (invKeys) might look like this:
export const invKeys = { // Base inventory query all: ['inventory'] as const,
// Inventory list list: (queries?: InventoryQueries) => [...invKeys.all, 'list', {queries}] as const,
// More keys...
detail: (id: string) => [...invKeys.details(), id] as const,
// Further keys...}Usage in Data Layer
The query keys are used in the data layer files to interact with the API. For example:
export const useGetInventoryById = (inventoryId?: string) => { const response = useQuery({ queryKey: invKeys.detail(inventoryId ?? ''), queryFn: () => svc.getInventoryById(inventoryId), enabled: inventoryId ? true : false, }) return {inventory: response.data, ...response}}Best Practices for Query Key Factory
- Descriptive Keys: Ensure that the keys are descriptive and clearly indicate their purpose.
- Consistency: Maintain a consistent structure for query keys across different data layers.
- Parametrization: Use parameters in query key functions for dynamic key generation.