Global vs Per-Query Configuration
What you'll learn: How to set sensible defaults for all queries in your QueryClient while still customizing behavior for individual queries when needed.
Understanding Configuration Layers
TanStack Query lets you configure behavior at two levels: globally when you create the QueryClient, and locally when you call useQuery. Think of global config as the house rules everyone follows by default, while per-query config is like making exceptions for specific situations.
Global configuration sets defaults for your entire app—things like how long data stays fresh, whether to refetch on window focus, or retry behavior. But sometimes a particular query needs different rules.
Setting Global Defaults
When creating your QueryClient, pass default options:
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 60000, // 1 minute
cacheTime: 300000, // 5 minutes
refetchOnWindowFocus: true,
retry: 3,
},
},
});
Now every query inherits these settings automatically.
Overriding Per Query
Individual queries can override any global setting:
const { data } = useQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
staleTime: 0, // Override: always stale
refetchOnWindowFocus: false, // Override: never refetch on focus
// Other globals still apply: cacheTime, retry
});
Only the options you specify override; the rest inherit from global config.
The Strategy
Set sensible defaults globally for typical API behavior, then override only when a query has unique needs. Real-time data might need staleTime: 0, while static reference data might need staleTime: Infinity. This keeps your code DRY while maintaining flexibility.
Key Takeaway: Global QueryClient configuration provides consistent defaults across your app, while per-query options let you fine-tune behavior for specific data needs without repeating yourself.