Subtitle:
React Query hook for accessing and manipulating the QueryClient instance
Core Idea:
useQueryClient provides direct access to the QueryClient instance, enabling programmatic control over the query cache and offering methods to manage queries and mutations outside the context of individual hooks.
Key Principles:
- Cache Management:
- Provides methods to interact with and modify the query cache.
- Query Control:
- Enables manual triggering of refetches, cache invalidation, and updates.
- Global Access:
- Offers centralized control of query state from any component.
Why It Matters:
- Imperative Control:
- Allows for cache manipulation in response to events outside normal data flow.
- Cross-Component Coordination:
- Enables updating or invalidating queries from unrelated components.
- Advanced Patterns:
- Supports complex caching strategies and optimistic updates.
How to Implement:
- Access the Client:
- Import and call
useQueryClient()within a component.
- Import and call
- Identify Targets:
- Define query keys for operations that need to be performed.
- Apply Operations:
- Use client methods like invalidateQueries, setQueryData, or prefetchQuery.
Example:
-
Scenario:
- Invalidating user data across the application after a profile update.
-
Application:
import { useQueryClient } from '@tanstack/react-query';
function LogoutButton() {
const queryClient = useQueryClient();
const handleLogout = async () => {
await fetch('/api/logout', { method: 'POST' });
// Clear all query cache data when user logs out
queryClient.clear();
};
return (
);
}
```
- Result:
- Upon logout, all cached queries are cleared, ensuring no sensitive data remains.
Connections:
- Related Concepts:
- React Query - Parent library
- useQuery - Data fetching hook
- useMutation - Data mutation hook
- QueryClient - The underlying client object
- Broader Concepts:
References:
- Primary Source:
- TanStack Query documentation on useQueryClient
- Additional Resources:
- "Advanced React Query Patterns" by Tanner Linsley
Tags:
#react-query #cache-management #query-control #tanstack #advanced-patterns
Connections:
Sources:
- From: useQuery