乐闻世界logo
搜索文章和话题

How does React Query's caching mechanism work, and how to configure and manage the cache?

3月6日 21:34

React Query's caching mechanism is one of its core features, working in the following ways:

How Caching Works

  1. 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.

  2. Cache Storage: Query results are stored in memory, organized by query keys.

  3. Cache State: Each cache item contains data, timestamps, status (fresh/stale/invalidated), etc.

  4. 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

  1. Global Configuration: Configure default cache behavior through QueryClient

    javascript
    const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: 5 * 60 * 1000, // 5 minutes cacheTime: 10 * 60 * 1000, // 10 minutes retry: 3, }, }, });
  2. Per-Query Configuration: Override default settings in useQuery

    javascript
    const { data } = useQuery('todos', fetchTodos, { staleTime: 10 * 60 * 1000, cacheTime: 30 * 60 * 1000, refetchOnWindowFocus: false, });

Cache Management

  1. Invalidate Data: Manually mark queries as invalid to trigger refetching

    javascript
    queryClient.invalidateQueries('todos');
  2. Update Data: Directly update data in the cache

    javascript
    queryClient.setQueryData('todos', oldTodos => [...oldTodos, newTodo]);
  3. Prefetch Data: Fetch data in advance that might be needed

    javascript
    queryClient.prefetchQuery('user-1', () => fetchUser(1));
  4. Remove Cache: Remove data from the cache

    javascript
    queryClient.removeQueries('todos');
  5. Reset Cache: Clear all cached data

    javascript
    queryClient.resetQueries();

Cache Strategy Best Practices

  1. Set appropriate staleTime based on data update frequency
  2. Increase cacheTime for frequently accessed but infrequently changed data
  3. Use prefetching to improve user experience
  4. Properly handle invalidation of related queries after mutations
  5. 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.

标签:React