Blog>
Snippets

Utilizing Cache Time Settings to Optimize React Query Cache Behavior

Illustrates how to adjust cache time settings in React Query using TanStack Config to optimize cache behavior, effectively managing memory and improving application responsiveness.
import { QueryClient } from '@tanstack/react-query';
First, import QueryClient from '@tanstack/react-query' to initialize and configure React Query.
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      cacheTime: 1000 * 60 * 5, // 5 minutes
    },
  },
});
Create a new QueryClient instance. Use the defaultOptions to set a custom cache time. In this example, cacheTime is set to 5 minutes (300,000 milliseconds). This means cached data will be deleted after 5 minutes of inactivity.
export default queryClient;
Export the queryClient instance so it can be used throughout your application.