Blog>
Snippets

Caching and Automatic Refetching

Show how to configure caching strategies and enable automatic refetching with React Query to keep the data fresh.
import { useQuery } from 'react-query';

const fetchData = async () => {
  const response = await fetch('https://example.com/api/data');
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
};

function App() {
  const { data, error, isLoading } = useQuery('dataKey', fetchData, {
    cacheTime: 5 * 60 * 1000, // Cache the data for 5 minutes
    staleTime: 60 * 1000, // Data is fresh for 1 minute
    refetchOnWindowFocus: true // Automatically refetch on window focus
  });

  if (isLoading) return 'Loading...';
  if (error) return 'An error has occurred: ' + error.message;

  return (
    <div>
      <h1>Data</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}
This code snippet defines a React component that uses the 'useQuery' hook from React Query to fetch data from an API. It configures the caching strategy with a cache time of 5 minutes and specifies that the data should be considered fresh for 1 minute. Automatic refetching is enabled on window focus to keep the data fresh.