React Query's caching mechanism is one of its core features, working in the following ways:
How Caching Works
-
Query Keys: React Query uses query keys (usually strings or arrays) as unique identifiers for caching. Requests with the same query key share cached data.
-
Cache Storage: Query results are stored in memory, organized by query keys.
-
Cache State: Each cache item contains data, timestamps, status (fresh/stale/invalidated), etc.
-
Cache Lifecycle:
- Fresh: Data was recently fetched, no need to re-request
- Stale: Data has exceeded staleTime but not gcTime
- Invalidated: Data was manually marked as invalid
- Garbage Collection: Data exceeding gcTime is removed from cache
Cache Configuration
-
Global Configuration: Configure default cache behavior through QueryClient
javascriptconst queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: 5 * 60 * 1000, // 5 minutes cacheTime: 10 * 60 * 1000, // 10 minutes retry: 3, }, }, }); -
Per-Query Configuration: Override default settings in useQuery
javascriptconst { data } = useQuery('todos', fetchTodos, { staleTime: 10 * 60 * 1000, cacheTime: 30 * 60 * 1000, refetchOnWindowFocus: false, });
Cache Management
-
Invalidate Data: Manually mark queries as invalid to trigger refetching
javascriptqueryClient.invalidateQueries('todos'); -
Update Data: Directly update data in the cache
javascriptqueryClient.setQueryData('todos', oldTodos => [...oldTodos, newTodo]); -
Prefetch Data: Fetch data in advance that might be needed
javascriptqueryClient.prefetchQuery('user-1', () => fetchUser(1)); -
Remove Cache: Remove data from the cache
javascriptqueryClient.removeQueries('todos'); -
Reset Cache: Clear all cached data
javascriptqueryClient.resetQueries();
Cache Strategy Best Practices
- Set appropriate staleTime based on data update frequency
- Increase cacheTime for frequently accessed but infrequently changed data
- Use prefetching to improve user experience
- Properly handle invalidation of related queries after mutations
- Use hierarchical query keys (e.g., ['users', userId, 'todos']) for more granular cache control
By properly configuring and managing the cache, you can significantly improve application performance, reduce unnecessary network requests, and ensure data freshness.