Blog>
Snippets

Avoiding Common Pitfalls: Correct Timeout Settings

Provide a practical example of setting an appropriate query timeout in React Query to prevent long-running queries, including tips on balancing usability and resource optimization.
import { QueryClient, QueryClientProvider } from 'react-query';

// Create a QueryClient instance
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      // Set an appropriate timeout for all queries to avoid long-running requests
      networkTimeout: 10000, // 10 seconds
      // Adjust refetching behavior to optimize usability and resource usage
      refetchOnWindowFocus: false,
      staleTime: 5 * 60 * 1000, // 5 minutes to reduce the frequency of refetches
    },
  },
});

// Provide the QueryClient to your application
function App() {
  return (
    <QueryClientProvider client={queryClient}>
      {/* The rest of your application */}
    </QueryClientProvider>
  );
}
This code sets up a QueryClient instance with a global configuration for all queries used in a React application. It specifies a network timeout of 10 seconds to prevent long-running queries from hanging indefinitely. It disables refetching on window focus to optimize resource usage and sets a stale time of 5 minutes to balance between usability (having relatively fresh data) and reducing the frequency of refetches, which saves resources.