Optimizing caching with query configuration

Configure React Query to optimally cache data based on expected mutation or fetch frequency, showcasing how to adjust cache time and stale time settings.
import { QueryClient, QueryCache } from 'react-query';

// Creating a new QueryClient instance
const queryClient = new QueryClient({
  queryCache: new QueryCache({
    defaultConfig: {
      queries: {
        // Data is considered fresh for 5 minutes
        staleTime: 5 * 60 * 1000,
        // Cache data is garbage collected after 30 minutes
        cacheTime: 30 * 60 * 1000,
        // Retry failed requests twice before throwing an error
        retry: 2,
        // Refetch data in the background if it becomes stale
        refetchOnWindowFocus: true
This code snippet configures the caching behavior of React Query for optimal performance based on expected mutation and fetch frequency. It sets the stale time to 5 minutes, meaning data will be considered fresh for this duration and won't be refetched. The cache time is set to 30 minutes, after which unused data will be removed from the cache. It also configures automatic retries for failed requests and enables background refetching of stale data on window focus.