Sub topic 2
Setting up QueryClient and QueryClientProvider
This chapter assumes you know React function components and hooks, async/await, and the basics of fetch and HTTP status codes. You should also have installed @tanstack/react-query (version 5) in a React and TypeScript project.
What the QueryClient does
A QueryClient is the object that owns the query cache and the default settings for every query and mutation in your app. Hooks such as useQuery and useMutation do not store anything themselves. They read from and write to the client.
React components find the client through context. QueryClientProvider puts a client into that context, so every component below it can call the hooks.
Creating the client and the provider
Create one client and wrap the top of your tree with the provider.
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
const queryClient = new QueryClient()
export function App() {
return (
<QueryClientProvider client={queryClient}>
<Todos />
</QueryClientProvider>
)
}Todos is a component you will write in the next chapter. Any component rendered inside the provider can now use query hooks. A component outside the provider throws an error when it calls a hook, because it finds no client in context.
Where to create the client
Create the client outside your component, as in the example above. The cache lives inside the client. If you wrote new QueryClient() in the body of App, React would build a new client on every render and you would lose all cached data each time App re-rendered.
If you must create the client inside a component, keep it in state so it is created only once:
import { useState } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
export function App() {
const [queryClient] = useState(() => new QueryClient())
return (
<QueryClientProvider client={queryClient}>
<Todos />
</QueryClientProvider>
)
}This pattern matters later with server rendering, where each request needs its own client. For a client-only app, the module-level client is simpler.
Setting defaults
The QueryClient constructor accepts defaultOptions. These apply to every query unless a query overrides them. Later chapters explain staleTime and retry in detail. For now, this shows where they go:
import { QueryClient } from '@tanstack/react-query'
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 60 * 1000,
retry: 1,
},
},
})Set defaults only when you have a reason. The built-in defaults are a good starting point, and a query can always override a default with its own option.
Common errors
- "No QueryClient set, use QueryClientProvider to set one." A component called a query hook outside the provider. Move the provider higher in the tree.
- Cache resets on every render. The client is created inside a component body without
useState. Move it to module scope or wrap it inuseState. - Multiple clients by accident. Two providers with different clients give you two separate caches, so data fetched in one is invisible to the other. Use one client unless you want that isolation.
Exercise
A teammate writes const queryClient = new QueryClient() inside the App function body, above the return. The app works, but cached data disappears whenever App re-renders. Why does this happen, and what are two ways to fix it?
Show answer
Each render of App creates a new QueryClient with an empty cache, so the old cache is discarded. Fix it by moving new QueryClient() to module scope, outside the component, or by creating it once with useState(() => new QueryClient()).