Blog>
Snippets

Customizing Query Caching Strategies

Provide an example of how to customize caching settings for individual queries using React Query's query options to fine-tune performance and user experience.
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';

const fetchPopularMovies = async () => {
  const { data } = await axios.get('/api/movies/popular');
  return data;
};

function PopularMovies() {
  const { data, error, isLoading } = useQuery(['popularMovies'], fetchPopularMovies, {
    // Customizing the cache time for this specific query
    cacheTime: 1000 * 60 * 60 * 24, // 24 hours
    staleTime: 1000 * 60 * 5, // 5 minutes
    refetchOnWindowFocus: false
  });

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>An error occurred: {error.message}</div>;

  return (
    <ul>
      {data.map(movie => (
        <li key={movie.id}>{movie.title}</li>
      ))}
    </ul>
  );
}
This code demonstrates how to customize caching strategies for a specific query using React Query. It fetches a list of popular movies from an API and customizes the cache settings to store the fetched data for 24 hours with a stale time of 5 minutes. It also disables refetching when the window regains focus for this query.