Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 38 ยท Getting Started

QueryClient and QueryClientProvider

Learn what the QueryClient is, how QueryClientProvider shares it, how to set default options for every query, and the mistakes that create a fresh cache by accident.

Every TanStack Query feature goes through one object: the QueryClient. It owns the cache, remembers the default options and gives you methods to read, write and invalidate data. The QueryClientProvider is a React component that makes one client available to every hook below it. Getting these two right is the whole setup, and most "my cache keeps resetting" bugs come from getting them slightly wrong.

The client owns the cache

A QueryClient holds a QueryCache (all queries) and a MutationCache (all mutations). Hooks like useQuery do not store data themselves. They observe an entry in the client's cache and re-render when it changes.

JSX
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";

const queryClient = new QueryClient();

function Root() {
  return (
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  );
}

Two facts follow from this design:

  • If two components use the same query key and the same client, they share one cache entry and one request.
  • If you create a new client, you get a new, empty cache. Everything is fetched again.

Create the client once

The classic mistake is creating the client inside a component body:

JSX
function Root() {
  // Wrong: a new, empty cache on every render of Root
  const queryClient = new QueryClient();
  return <QueryClientProvider client={queryClient}><App /></QueryClientProvider>;
}

Whenever Root re-renders, the cache is thrown away. Create the client at module level (client-only apps), or keep it stable with useState when you need it inside a component (for example in server-rendered apps, where each request needs its own client):

JSX
function Root() {
  const [queryClient] = useState(() => new QueryClient());
  return <QueryClientProvider client={queryClient}><App /></QueryClientProvider>;
}

The lazy initializer runs once per component instance, so the client survives re-renders.

Seeing the shared cache

In this demo three separate components ask for the same key. Watch the request counter: there is one request, not three.

Three components, one request

Three observers, one entry, one request. This is deduplication, and it only works because all three share a client through the provider.

Default options

The QueryClient constructor accepts defaultOptions that apply to every query and mutation unless a hook overrides them:

JSX
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 60 * 1000,     // data stays fresh for one minute
      gcTime: 10 * 60 * 1000,   // unused data lives ten minutes
      retry: 1,                 // retry a failed request once
      refetchOnWindowFocus: false,
    },
    mutations: {
      retry: 0,
    },
  },
});

Per-hook options always win: useQuery({ queryKey, queryFn, staleTime: 0 }) overrides the default for that query. You can also set defaults for one key prefix with queryClient.setQueryDefaults(["todos"], { staleTime: 5000 }). Defaults are the right place for decisions that apply app-wide; they keep individual hooks short.

Here is a demo where the default retry is changed. The query function fails twice and then succeeds. With retry: 3 the user never sees an error.

Default retry option

Using the client directly

Inside a component, useQueryClient() returns the client from the nearest provider. You use it for imperative work: reading the cache, invalidating after a mutation, prefetching.

JSX
import { useQueryClient } from "@tanstack/react-query";

function RefreshButton() {
  const queryClient = useQueryClient();
  return (
    <button onClick={() => queryClient.invalidateQueries({ queryKey: ["todos"] })}>
      Refresh todos
    </button>
  );
}

Outside React (a router loader, a test, a plain module) you use the client object itself. The hook only exists to find the provider's client. You will meet the main methods in Mutations, Invalidation and Cache Methods.

Several clients, nested providers

A provider can be nested, and the inner one wins for everything below it. That is occasionally useful for an isolated widget with its own cache and defaults, but most apps need exactly one client. If you pass a client explicitly as the second argument of a hook (useQuery({...}, queryClient)), it overrides the provider, which is handy in libraries that must not depend on the host app's provider.

A useQuery rendered outside any provider throws "No QueryClient set, use QueryClientProvider to set one". Check that your provider sits above every component that uses a hook, including portals and modals that render in another tree.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where is fetched data actually stored?

    Hooks observe entries in the client's QueryCache. That is why two components with the same key share data.
  2. 2. Why is new QueryClient() inside a component body a bug?

    A new client has an empty cache. Create it at module level or keep it with useState(() => new QueryClient()).
  3. 3. A hook sets staleTime: 0 while defaultOptions sets staleTime to one minute. Which value applies to that hook?

    Options passed to the hook take precedence over client defaults.
  4. 4. What does useQueryClient() return?

    It reads the client from context, so you can call methods such as invalidateQueries.

Summary

  • The QueryClient owns the cache and the default options; QueryClientProvider shares it through React context.
  • Create the client once: module level, or useState(() => new QueryClient()).
  • Same client plus same key means one cache entry and one request.
  • defaultOptions set app-wide behavior; options on a hook override them.
  • useQueryClient() gives you the client for imperative calls.

Next: Query Keys