Type-Safe React Query Optimizations

Showcase how to set up query prefetching and cache management in a type-safe manner, leveraging TypeScript for better performance optimizations.
import { useQuery, useQueryClient } from 'react-query';
import { fetchCarDetails } from './api';

interface CarDetails {
  id: number;
  make: string;
  model: string;
  year: number;

export const usePrefetchCarDetails = () => {
  const queryClient = useQueryClient();
  return async (carId: number) => {
    await queryClient.prefetchQuery<CarDetails, Error>(['carDetails', carId], () => fetchCarDetails(carId));
Defines a TypeScript interface for car details and a custom hook to prefetch car details using React Query. The prefetching is type-safe, ensuring that both the fetched data and the error conform to specific types.
import { QueryClient } from 'react-query';

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      cacheTime: 5 * 60 * 1000, // cache the data for 5 minutes
      staleTime: 60 * 1000, // mark data as stale after 1 minute
      refetchOnWindowFocus: false, // disable refetching on window focus

export default queryClient;
Creates a QueryClient instance with customized caching strategies. It sets data to be cached for 5 minutes and marked as stale after 1 minute. Additionally, it disables refetching data on window focus for performance optimization.