Blog>
Snippets

Implementing Cache Eviction Policies

Illustrate how to define and apply cache eviction policies to manage and limit the size of MutationCache, avoiding memory leaks.
import { QueryClient, MutationCache } from 'react-query';
First, import QueryClient and MutationCache from react-query.
const mutationCache = new MutationCache({
  // Set a cacheTime for each mutation's result
  cacheTime: 1000 * 60 * 5, // 5 minutes
  // Implement a custom eviction policy
  onCacheAdd: (mutation) => {
    // Check the size of the cache
    if (mutationCache.getAll().length > 50) { // Assuming a max of 50 mutations to store
      // Find the oldest mutation based on timestamp
      const oldestMutation = mutationCache.getAll().reduce((oldest, current) => {
        return current.state.data.timestamp < oldest.state.data.timestamp ? current : oldest;
      });
      // Remove the oldest mutation to respect the max size
      mutationCache.remove(oldestMutation);
    }
  }
});
Creates a new MutationCache with a custom eviction policy. It limits the cache to store a maximum of 50 mutation results. When adding a new mutation result, if the cache is full, it finds and removes the oldest mutation to make space.
const queryClient = new QueryClient({
  mutationCache
});
Create a new QueryClient instance and configure it to use the custom mutationCache with the eviction policy applied.