Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 38 ยท Getting Started

Installing and Setting Up TanStack Query

Install TanStack Query v5, create a QueryClient, wrap your React app in QueryClientProvider, set sensible default options and learn where the client should live.

Setting up TanStack Query takes three steps: install the package, create one QueryClient, and hand it to your component tree with a provider. This lesson walks through each step, explains the defaults the client ships with, and shows the mistakes that cause surprising behavior later.

Install

In a real project (Vite, Next.js, Remix or any React setup) you add the package from npm. These commands are read-only here, because the site cannot run a package manager.

Terminal
npm install @tanstack/react-query
# optional, but very useful while learning:
npm install -D @tanstack/react-query-devtools
# optional lint rules that catch missing query keys:
npm install -D @tanstack/eslint-plugin-query

TanStack Query v5 needs React 18 or newer. It ships its own TypeScript types, so there is no @types package to add. The live examples in this course use an import map instead of npm, which is why each one starts with a <script type="importmap"> block that maps the names react, react-dom/client and @tanstack/react-query to pinned CDN builds.

Create one QueryClient

The QueryClient owns the query cache and the mutation cache. Everything you fetch lives in it, so there should normally be exactly one for the whole app.

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

const queryClient = new QueryClient();

Create it outside your components, at module level. If you write new QueryClient() inside a component body, every re-render builds a fresh, empty cache and your data vanishes. (Server-rendered apps are the exception: they create a client per request, which a later lesson covers.)

Provide it to your tree

Hooks such as useQuery find the client through React context. Wrap your app once, near the root:

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

root.render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>
);

Without the provider, any useQuery call throws "No QueryClient set, use QueryClientProvider to set one".

Default options

A bare new QueryClient() already works, but you can set defaults for every query and mutation in the app:

JSX
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 30_000,        // data is fresh for 30 seconds
      gcTime: 10 * 60_000,      // unused data is kept for 10 minutes
      retry: 1,                 // retry a failed request once
      refetchOnWindowFocus: false,
    },
    mutations: {
      retry: 0,
    },
  },
});

Per-query options always win over these defaults. The built-in defaults are worth memorizing, because they explain most "why did it refetch?" questions:

Option Default Meaning
staleTime 0 Data is stale immediately, so a new observer triggers a refetch
gcTime 5 minutes Unused cache entries are removed after this
retry 3 Failed queries retry three times with exponential backoff
refetchOnWindowFocus true Stale queries refetch when the tab regains focus
refetchOnReconnect true Stale queries refetch when the network returns

Mutations default to retry: 0.

JS Inspecting the defaults

Press Run (or Ctrl + Enter) to see the console output here.

No output.

defaultQueryOptions is a handy way to see what a query will really use. Notice that gcTime came from the query itself, while staleTime and retry came from the client defaults.

A complete minimal app

This example puts everything together: a module-level client with defaults, the provider, and a component that reads the client with useQueryClient. It prints how many queries are in the cache.

A complete minimal setup

CacheInfo does not re-render when the cache changes, because it reads the cache directly instead of subscribing to it. That is fine for a one-off peek, but it shows why you normally use useQuery: hooks subscribe, direct reads do not.

Where to put the setup

A typical Vite project keeps it small:

TEXT
src/
  main.jsx        <- creates root, QueryClient, provider
  api/            <- fetch functions (getTodos, getUser)
  queries/        <- query keys and queryOptions per feature
  components/

Keeping the QueryClient in main.jsx (or a tiny queryClient.js module) also lets non-React code, such as a router loader, import the same instance.

Do not create the client inside a component with new QueryClient() unless you wrap it in useState(() => new QueryClient()). A new client on every render means a new, empty cache on every render.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should you normally create the QueryClient in a client-side React app?

    One client holds the cache for the whole app. Creating it in a component would reset the cache on every render.
  2. 2. What is the default staleTime?

    staleTime defaults to 0. The 5 minute default belongs to gcTime, which controls how long unused data stays in memory.
  3. 3. What happens if you call useQuery outside a QueryClientProvider?

    Hooks read the client from context, so a missing provider is an error.
  4. 4. Which value wins when a query sets retry: 5 and the client default is retry: 1?

    Options passed to a specific query override defaultOptions.

Summary

  • Install @tanstack/react-query (plus optional devtools and ESLint plugin); React 18+ is required.
  • Create one QueryClient at module level and share it with QueryClientProvider.
  • Defaults: staleTime 0, gcTime 5 minutes, retry 3, refetch on window focus and reconnect.
  • Set app-wide defaults in defaultOptions; per-query options override them.

Next: Your First Query