Sub topic 2
Setting up QueryClient and QueryClientProvider
This chapter assumes you know React function components and hooks, TypeScript basics, and how fetch and Promises work. It also assumes you have read the previous chapter on why server state differs from client state. Here you will create the object that holds all server state and make it available to your components.
What the QueryClient is
A QueryClient is an object that owns the query cache and the default settings for every query and mutation in your app. Hooks such as useQuery do not store data themselves. They ask the client for a cache entry, subscribe to it, and re-render when it changes.
The QueryClientProvider is a React component that places a client in React context. Every component below it can then reach the client through hooks. Without a provider, useQuery throws an error, because it has no client to talk to.
The minimal setup
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>
)
}Install the package first with npm install @tanstack/react-query. This tutorial uses version 5. The provider takes one required prop, client. Anything rendered inside it, at any depth, can use queries and mutations.
Where the client lives matters
The cache lives inside the client object. If you lose the client, you lose the cache. That makes the place where you create it important.
Create it outside the component
In the example above, queryClient is created at module level. The module is evaluated once, so the same client is used for the whole life of the page. This is the simplest and safest pattern for apps that render only in the browser.
Do not create it inside a render
This version looks similar, but it is a bug:
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
export function App() {
// Wrong: a new client, with an empty cache, on every render of App
const queryClient = new QueryClient()
return (
<QueryClientProvider client={queryClient}>
<Todos />
</QueryClientProvider>
)
}Each time App re-renders, it builds a new client with an empty cache. Every query then starts over from the pending state and refetches. Symptoms include loading spinners that reappear for no reason and a network tab full of repeated requests.
Server rendering needs a client per request
If your app renders on a server, a module-level client would be shared by all users and all requests. Cached data from one user could leak into another user's page. In that case, create the client inside the component, but keep it stable with useState:
import { useState } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
export function Providers({ children }: { children: React.ReactNode }) {
const [queryClient] = useState(() => new QueryClient())
return (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}The function passed to useState runs only on the first render, so the client survives re-renders. The last chapter of this tutorial covers server rendering in detail.
Setting default options
The QueryClient constructor accepts defaultOptions. These apply to every query or mutation that does not set its own value. You will meet staleTime, gcTime, and retries in later chapters. For now, treat them as settings you can choose once for the whole app.
import { QueryClient } from '@tanstack/react-query'
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 30 * 1000,
retry: 1,
},
mutations: {
retry: 0,
},
},
})With this client, query data counts as fresh for 30 seconds, a failed query is retried once, and mutations are never retried. An option set on an individual useQuery call overrides the default for that query only.
The built-in defaults are cautious. Data is stale immediately (staleTime: 0), and a failed query is retried three times. Changing defaults in one place is easier to maintain than repeating the same option on every hook.
| Option | Built-in default | What it controls |
|---|---|---|
| `staleTime` | `0` | How long fetched data is considered fresh |
| `gcTime` | 5 minutes | How long unused data stays in the cache |
| `retry` (queries) | `3` | Retries after a failed fetch |
| `retry` (mutations) | `0` | Retries after a failed mutation |
Using the client directly
Components can read the client with the useQueryClient hook. You need it to invalidate queries, read cache data, or write to the cache.
import { useQueryClient } from '@tanstack/react-query'
function RefreshButton() {
const queryClient = useQueryClient()
return (
<button onClick={() => queryClient.invalidateQueries({ queryKey: ['todos'] })}>
Refresh todos
</button>
)
}useQueryClient returns the client from the nearest provider. If no provider is above the component, it throws an error with the message "No QueryClient set, use QueryClientProvider to set one".
Outside React, such as in a router loader or a test, you can use the client object you created directly, since it is an ordinary JavaScript object.
Common errors
- "No QueryClient set" error. The component using a hook is rendered outside the provider. Check that the provider wraps the whole tree, including portals and test renders.
- Cache resets on every render. The client is created inside a component body. Move it out or wrap it in
useState. - Two clients in one app. Two providers with different clients give you two separate caches. An invalidation on one client does not affect queries on the other. Use one client unless you have a clear reason for isolation.
- Importing from the wrong package. In v5 the package is
@tanstack/react-query. Older tutorials import fromreact-query, which is version 3 and has a different API.
Nested providers
You can nest providers. A component uses the client from the nearest provider above it. This is rarely needed, but it can isolate a part of the page, such as an embedded widget, with its own cache and defaults. Treat it as an exception, since shared data will not cross the boundary.
Exercise
A teammate writes const queryClient = new QueryClient() inside the App component and wraps the tree in QueryClientProvider. Users report that loading spinners keep reappearing after unrelated state changes in App. Explain the cause and give two ways to fix it.
Show answer
Each render of App creates a new QueryClient with an empty cache, so all queries below it start from the pending state and refetch. Fix it by moving new QueryClient() to module level, outside the component. Alternatively, keep it inside the component with const [queryClient] = useState(() => new QueryClient()), which creates it only once per component instance.
Exercise
You want every query in your app to treat data as fresh for one minute and to retry failed requests twice. Where do you set this, and how can one query opt out?
Show answer
Pass defaultOptions: { queries: { staleTime: 60 * 1000, retry: 2 } } to the QueryClient constructor. A single query opts out by setting its own staleTime or retry in its useQuery options, which override the defaults for that query only.