Blog>
Snippets

Customizing Caches with QueryClient

Illustrate how to customize the caching strategy, including cache invalidation and garbage collection.
import { QueryClient } from '@tanstack/react-query';

// Creating a new QueryClient instance
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      // Data will be considered stale after 5 minutes
      staleTime: 5 * 60 * 1000,
      // Garbage collection will run to cleanup unused data after 30 minutes
      cacheTime: 30 * 60 * 1000,
      // Automatically refetch data in the background if data becomes stale
      refetchOnMount: 'always',
      // Define a custom function to determine when to retry failed queries
      retry: (failureCount, error) => error.status !== 404 || failureCount < 2
    }
  }
});
This code snippet demonstrates how to create a new instance of QueryClient with custom default options for caching strategy, including setting stale times, cache times, refetch behaviors, and retry logic. These customizations help in defining when the cached data is considered stale, how long unused data should be kept in cache before being garbage-collected, and under what conditions the data should be refetched or retries for failed queries should occur.
queryClient.setQueryData('todos', oldData => ({ ...oldData, completed: true }));
queryClient.invalidateQueries('todos');
Here, `setQueryData` is used to update the cache for a specific query. This can be useful when you know the new state of your data after a mutation but do not want to wait for a refetch. Then, `invalidateQueries` is called to manually invalidate the cache for all 'todos' queries, signaling that this data may be out of date and should be refetched upon the next access. This demonstrates manual cache invalidation, which is a powerful feature when dealing with mutations or any operations that alter server-side data.
queryClient.getQueryCache().subscribe(query => {
  if (!query.state.data) {
    // Perform cleanup or other actions when a query has no data
    console.log(`Query '${query.queryKey}' is empty and could be garbage collected`);
  }
});
This example shows how to subscribe to all query cache events using `getQueryCache().subscribe`. Here, a check is performed to see if any query has no data, potentially indicating an opportunity for garbage collection or triggering other actions based on the emptiness of specific queries. This can be part of a custom strategy for monitoring and managing the cache more proactively.