Blog>
Snippets

Optimizing Cache Behavior

Configure React Query's cache settings to manage how long fetched data is stored and reused across the application.
import { QueryClient } from 'react-query';

// Configure React Query's global cache settings
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      cacheTime: 1000 * 60 * 5, // 5 minutes in milliseconds
      staleTime: 1000 * 60, // 1 minute
    },
  },
});
This code snippet sets up a QueryClient instance from React Query with custom cache settings. The cacheTime is set to 5 minutes, meaning cached data will be considered fresh for this duration before it's automatically marked for garbage collection if not accessed. The staleTime is set to 1 minute, dictating how long fetched data is considered fresh and won't be refetched on access until this time elapses.
import { useQuery } from 'react-query';

function fetchTodos() {
  return fetch('https://example.com/todos').then(res => res.json());
}

// Use React Query's useQuery hook with configurable stale and cache times
const { data, isLoading, error } = useQuery('todos', fetchTodos, {
  staleTime: 1000 * 60 * 5, // 5 minutes
  cacheTime: 1000 * 60 * 10, // 10 minutes
});
In this part of the code, the useQuery hook is utilized to fetch data (todos) from an API. The staleTime is set to 5 minutes, indicating that the data won't be considered stale and refetched for this period. The cacheTime is extended to 10 minutes, allowing the fetched data to live in the cache longer before being considered for garbage collection if not accessed, optimizing subsequent data retrieval operations.