Attributes: ✅ Recommended • 🔧 Fixable
Overview
The QueryClient contains the QueryCache, so you’d only want to create one instance of the QueryClient for the lifecycle of your application - not a new instance on every render. Creating a new QueryClient on every render will:- Reset your entire cache
- Cause all queries to refetch
- Break optimistic updates
- Cause performance issues
Rule Details
This rule prevents creating a new QueryClient instance inside a component function body, which would cause it to be recreated on every render.Examples
Incorrect Code
Correct Code
Exception: Server Components
It’s allowed to create a new QueryClient inside an async Server Component, because the async function is only called once on the server.
Server Component (Next.js App Router)
Common Patterns
App-Level Provider
The most common pattern is creating the QueryClient at the module level:App.tsx
Component-Level Provider
Sometimes you need a provider lower in the tree. UseuseState:
NestedProvider.tsx
Testing Setup
In tests, create a new client for each test:test-utils.tsx
Why useState Over useMemo?
useState is more reliable
useState is more reliable
useState with a function initializer is the recommended approach because:- Guaranteed single execution: The initializer function runs exactly once
- No dependencies: Unlike
useMemo, you can’t accidentally provide wrong dependencies - React concurrent mode safe: Works correctly with React 18+ concurrent features
- Clearer intent: Signals that this value should never change
Auto-Fix
This rule includes an auto-fixer that will wrap your QueryClient creation inuseState:
Multiple QueryClients
Sometimes you need multiple QueryClient instances (e.g., for isolated contexts):Framework-Specific Patterns
Next.js App Router
app/providers.tsx
Remix
app/root.tsx
Debugging
If you suspect your QueryClient is being recreated:Related Rules
- exhaustive-deps - Ensures proper query key dependencies
Further Reading
QueryClient
Learn about QueryClient configuration options
Important Defaults
Understand TanStack Query’s default behaviors