Blog>
Snippets

Optimizing React Query Cache

Illustrate the configuration of React Query's cache settings to optimize the performance of data fetching operations.
import { QueryClient, QueryClientProvider } from 'react-query';
Import necessary components from 'react-query'.
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5 * 60 * 1000, // Data is fresh for 5 minutes
      cacheTime: 30 * 60 * 1000, // Cache retained for 30 minutes
      refetchOnWindowFocus: false
    }
  }
});
Configure default cache behavior. 'staleTime' defines how long the fetched data is considered fresh, while 'cacheTime' specifies the duration data remains in cache before it's garbage collected. 'refetchOnWindowFocus' disables refetching when the window regains focus.
function App() {
  return (
    <QueryClientProvider client={queryClient}>
      // Your app components go here
    </QueryClientProvider>
  );
}
Wrap your application with the QueryClientProvider to provide the configured React Query client throughout your React component tree.