Skip to content

Volume ITechnology

6.4.10 — TanStack Query: Fetching Server Data ​

On page 6.4.3 you loaded products by hand. It took a status variable, an effect, a cleanup flag, and a res.ok check. And the page still could not do five things a shop needs: show saved data instantly when you come back, send one request when two components ask for the same thing, retry when the network blinks, refresh when the user returns to the tab, and update every screen after an edit.

TanStack Query (also called React Query) does all five. It is the most widely used way to get server data into a React app, and it is what interviewers mean when they ask "how do you fetch data in React?" This page teaches the reading half: useQuery. Page 6.4.11 teaches the writing half.

1. The idea: you do not own server data, you borrow a copy ​

Some data lives in your browser only: whether a menu is open, what is typed in a box. You own it. When you change it, it is changed.

Other data lives on a server: the product list, the user's orders. Your page holds a copy. The copy can be wrong at any moment, because someone else may have changed the original. You cannot "set" it. You can only ask again.

Page 6.4.6 called this server state. TanStack Query manages that copy for you. It remembers every answer, decides when an answer is too old, asks again in the background, and tells your components. You describe what you want. It handles when.

ProductListuseQuery(['products'])SearchSuggestionsuseQuery(['products'])ProductPage (later)useQuery(['products', 'p2'])QueryClient cache['products']data + status + age['products', 'p2']data + status + ageServerGET /api/productssent only once①②① one request for the two askers② the answer is saved under the keyNext visit: saved data shown instantly, refreshed in the background
TanStack Query sits between your components and the server. Each key is one entry in the cache. Two components that ask for the same key share one request and one answer. A component that appears later gets the saved data at once, and the library refreshes it quietly.

Each request you describe gets a key, which is its address in the cache. Two components that use the same key share one request and one answer (see the figure). A component that appears later is shown the saved answer at once while the library refreshes it quietly.

2. Set it up ​

bash
npm install @tanstack/react-query
tsx
// src/main.tsx
import { createRoot } from 'react-dom/client'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import App from './App'

const queryClient = new QueryClient()                                              // (1)

createRoot(document.getElementById('root')!).render(
  <QueryClientProvider client={queryClient}>                                       {/* (2) */}
    <App />
  </QueryClientProvider>,
)
  1. The QueryClient is the cache and the brain. You create one for the whole app, outside any component, so it is not recreated on each render.
  2. QueryClientProvider makes it available to all components below, through Context. This is the same idea as the Redux Provider on page 6.4.7. The provider holds the client object, which never changes, so it does not cause extra re-renders.

TanStack also ships Devtools, a small panel inside your page that shows every key, its data, and whether it is fresh or stale. Install @tanstack/react-query-devtools and put <ReactQueryDevtools /> inside the provider while you develop. It is the quickest way to understand what the cache is doing.

3. Your first query ​

First, one small helper for talking to the server. It does the res.ok check from page 6.4.3 once, so no query function repeats it.

ts
// src/api/client.ts
export async function getJson<T>(url: string, signal?: AbortSignal): Promise<T> {
  const res = await fetch(url, { signal })                                         // (1)
  if (!res.ok) throw new Error(`The server answered ${res.status}`)                // (2)
  return (await res.json()) as T
}
  1. signal is optional. It lets the library cancel the request if the component goes away or the key changes. (The browser's AbortSignal is the standard way to cancel a fetch.)
  2. fetch does not fail on 404 or 500, so we throw ourselves. TanStack Query treats a thrown error or a rejected promise as a failed query. If you forget this check, an error page would be treated as good data.

Now the component:

tsx
// src/components/ProductList.tsx
import { useQuery } from '@tanstack/react-query'
import { getJson } from '../api/client'

type Product = { id: string; name: string; priceCents: number }

export function ProductList() {
  const query = useQuery({
    queryKey: ['products'],                                                        // (1)
    queryFn: ({ signal }) => getJson<Product[]>('/api/products', signal),          // (2)
  })

  if (query.isPending) return <p>Loading products…</p>                              // (3)
  if (query.isError) return <p role="alert">Could not load: {query.error.message}</p>   // (4)

  return (
    <ul>
      {query.data.map((p) => (                                                      // (5)
        <li key={p.id}>{p.name}</li>
      ))}
    </ul>
  )
}
  1. queryKey is the address of this data in the cache. It is an array. Here it is just ['products'].
  2. queryFn is the function that fetches the data. It must return a promise. Whatever it resolves to is the data. TypeScript works out the type of query.data from it.
  3. isPending is true while there is no data yet for this key. This is the "waiting" situation from the three-state figure on page 6.4.3.
  4. isError is true when the function threw (after the retries, which come soon). query.error holds the error.
  5. By the time we reach this line, TypeScript knows the query succeeded, because both early returns are above it. So query.data is a Product[], not Product[] | undefined.

Compare this with the hand-written version from page 6.4.3. There is no useState, no useEffect, no ignore flag, no LoadState type. The race condition that ignore prevented is handled by the library. And it got all five missing features for free.

Version note: isPending, not isLoading ​

Older tutorials say isLoading. In version 5, isPending means "no data yet", and isLoading has a narrower meaning: "no data yet and a request is running right now". The difference matters when a query is switched off (enabled: false, section 8). Use isPending for "show the loading screen".

4. The query key, in detail ​

The key is the most important idea in the library. Get it right and everything else follows.

Rule: put everything the query function uses into the key. If the function depends on a value, that value goes in the key. Then a different value means a different key, a different cache entry, and a new request.

tsx
const [category, setCategory] = useState('kitchen')

const query = useQuery({
  queryKey: ['products', { category }],                                            // (1)
  queryFn: ({ signal }) =>
    getJson<Product[]>(`/api/products?category=${encodeURIComponent(category)}`, signal),
})
  1. The key includes category. When the user switches from 'kitchen' to 'garden', the key changes, so TanStack Query looks for ['products', { category: 'garden' }] in the cache. If it is there, the data is shown at once. If not, it fetches. And going back to 'kitchen' finds that entry again, still cached.

This replaces the dependency array and the race condition handling from page 6.4.3. Different keys are different entries, so a slow old answer can never be shown under the new key.

How keys are compared: the library turns the key into text, with object properties sorted. We checked:

text
['products', { a: 1, b: 2 }]  equals  ['products', { b: 2, a: 1 }]   → true   (property order does not matter)
['a', 'b']                    equals  ['b', 'a']                    → false  (array order matters)

A key factory ​

When you have several queries about products, typing the keys by hand in many files causes typos, and a typo is a silent bug (it simply creates a different cache entry). So keep all the keys of one feature in one small object:

ts
// src/api/products.ts
import { queryOptions } from '@tanstack/react-query'
import { getJson } from './client'

export type Product = { id: string; name: string; priceCents: number }

export const productKeys = {
  all: ['products'] as const,                                                      // (1)
  list: (filters: { category: string }) => [...productKeys.all, 'list', filters] as const,
  detail: (id: string) => [...productKeys.all, 'detail', id] as const,
}

export const productListOptions = (category: string) =>
  queryOptions({                                                                   // (2)
    queryKey: productKeys.list({ category }),
    queryFn: ({ signal }) =>
      getJson<Product[]>(`/api/products?category=${encodeURIComponent(category)}`, signal),
  })

export const productDetailOptions = (id: string) =>
  queryOptions({
    queryKey: productKeys.detail(id),
    queryFn: ({ signal }) => getJson<Product>(`/api/products/${id}`, signal),
  })
  1. all is the root. Every product key starts with it. This matters in the next page: invalidating ['products'] marks every key that starts with it as out of date, lists and details together. as const tells TypeScript the array has exactly these items, in this order.
  2. queryOptions is a small helper that bundles a key with its function. Anywhere you need this query, you write useQuery(productListOptions('kitchen')). The key and the function can no longer drift apart. And the same bundle can be used in a router loader or in queryClient.prefetchQuery, with full types.
tsx
const { data, isPending } = useQuery(productListOptions(category))

5. How fresh is the data? staleTime and gcTime ​

This is the part that makes people say "it refetches too much" or "it never refetches". There are two timers.

Freshused as it isno requestStaleshown at once, andrefreshed on mount or focusInactive (nobody uses it)kept in memory for gcTimethen deletedlasts staleTime(default 0: stale at once)lasts gcTime(default 5 minutes)staleTime = how long to trust data. gcTime = how long to remember it.
The life of one cache entry. While fresh, the saved data is used with no request. Once stale, the data is still shown at once, but a refresh runs when a component appears or the tab regains focus. When nobody uses it, it waits for gcTime and is then deleted.

staleTime: how long saved data counts as fresh. Fresh data is used as it is, with no request. The default is 0, which means data is stale immediately. That sounds wasteful but it is a safe default: the user always sees what is saved at once, and a quiet check runs in the background to make sure it is still right.

gcTime: how long to keep data that nobody is using. "gc" stands for garbage collection, which means cleaning up what is no longer needed. When the last component using a key goes away, the entry stays in the cache for gcTime, then is deleted. The default is 5 minutes. If the user comes back within 5 minutes, the old data appears instantly. (In version 4 this option was called cacheTime.)

We measured both behaviours. With the default staleTime of 0, we unmounted a list and mounted it again. On the very first render of the second mount, the data was already there, and a refetch was running in the background (isFetching was true, isPending was false). Fetch count went from 1 to 2. With staleTime: 60_000 the second mount used the saved data and sent no request at all (the count stayed at 1). And with gcTime: 30 ms, the entry was deleted from the cache shortly after the last component left.

How to pick staleTime:

The data isExamplestaleTime
Changes constantlystock levels, a live score0 (default)
Changes now and thenproduct list, user's orders30 seconds to a few minutes
Almost never changescountry list, settings10 minutes or more, or Infinity

Set a sensible default once, for the whole app:

tsx
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 60_000,                                                           // one minute
    },
  },
})

6. Reading the status flags ​

A query has two separate pieces of information, and mixing them up causes most confusion.

FieldAnswers the questionValues
statusDo I have data?'pending' (no), 'error' (it failed), 'success' (yes)
fetchStatusIs a request running right now?'fetching', 'idle', 'paused' (no network)

These are independent. A query can be success and fetching at the same time. That is exactly the "show saved data while refreshing" case. So:

You want toUse
Show a full-page loader for the very first loadisPending
Show a small "refreshing…" spinner while old data stays visibleisFetching && !isPending
Show an errorisError (and error)
Know whether the data on screen is a stand-inisPlaceholderData (section 8)

7. When does it fetch again? ​

By default, a stale query refetches when:

  1. A component using it mounts (appears on the screen).
  2. The browser window regains focus. The user comes back from another tab and sees fresh data, with no code from you.
  3. The network reconnects.
  4. You call refetch(), or you invalidate it (next page).
  5. A timer, if you ask for one: refetchInterval: 10_000 refetches every ten seconds, for a live dashboard.

And what happens when a request fails? By default it retries three times with a growing pause (about 1, 2, then 4 seconds) before it gives up and shows the error. We counted: a function that always throws was called 4 times (the first try plus 3 retries). With retry: false it was called once. Retrying is right for network blips and wrong for a "404 not found", which will never succeed. You can set retry: false on queries where a failure is final, or give a function that decides.

tsx
useQuery({
  queryKey: ['products'],
  queryFn: () => getJson<Product[]>('/api/products'),
  retry: 1,                       // try once more, then show the error
  refetchOnWindowFocus: false,    // do not refresh when the tab regains focus
  refetchInterval: 30_000,        // refresh every 30 seconds
})

Two components, one request ​

Put two components that use ['products'] on the same page. How many requests go out? We counted: one. The first to mount starts the request. The second sees it already running and just waits for the same answer. This is deduplication, and it is why you can call useQuery freely in any component that needs the data, instead of fetching once at the top and passing it down. Each component states what it needs. The cache makes sure it is fetched only once.

8. Controlling a query ​

Wait until you have what you need: enabled ​

Sometimes a query must not run yet. Example: load a customer's orders only after you know the customer's id.

tsx
const customer = useQuery(customerOptions())            // returns { id: ... } or undefined

const orders = useQuery({
  queryKey: ['orders', customer.data?.id],
  queryFn: ({ signal }) => getJson<Order[]>(`/api/customers/${customer.data!.id}/orders`, signal),
  enabled: customer.data !== undefined,                 // do not run until we have an id
})

While enabled is false, the query does nothing. We checked: the function was never called, and the state was status: 'pending', fetchStatus: 'idle'. That is a case where isPending is true but no request is running, which is why isLoading (pending and fetching) is false there.

Pages without a flash: placeholderData ​

A paged list: when the user clicks "Next", the key changes (['products', { page: 2 }]), the new key has no data, and the list would be replaced with a loading screen. Often better is to keep the old page visible until the new one arrives.

tsx
import { keepPreviousData, useQuery } from '@tanstack/react-query'

const [page, setPage] = useState(1)

const query = useQuery({
  queryKey: ['products', { page }],
  queryFn: ({ signal }) => getJson<Product[]>(`/api/products?page=${page}`, signal),
  placeholderData: keepPreviousData,                                               // (1)
})
  1. keepPreviousData says "while the new key has no data, show the data from the previous key". We tested it: right after clicking Next, the screen still showed page 1's data with isPlaceholderData set to true. When page 2 arrived, it was replaced. You can use isPlaceholderData to dim the list a little while it waits.

Change the shape of the data: select ​

select transforms what the cache holds into what this component needs. The cache keeps the full list. A badge only needs the count.

tsx
const count = useQuery({
  ...productListOptions('kitchen'),
  select: (products) => products.length,
})

The badge component re-renders only when the result of select changes, not whenever the list changes in a way that keeps the same length. It is the same idea as a selector in Redux and Zustand.

9. Infinite lists: "Load more" ​

A feed that loads the next batch when the user clicks "Load more" or scrolls is a different shape from page numbers. The next request depends on what the last one returned. TanStack Query has useInfiniteQuery for it.

tsx
// src/components/ProductFeed.tsx
import { useInfiniteQuery } from '@tanstack/react-query'
import { getJson } from '../api/client'

type Page = { items: { id: string; name: string }[]; nextCursor: string | null }

export function ProductFeed() {
  const query = useInfiniteQuery({
    queryKey: ['feed'],
    initialPageParam: '',                                                          // (1)
    queryFn: ({ pageParam, signal }) =>
      getJson<Page>(`/api/feed?cursor=${encodeURIComponent(pageParam)}`, signal),  // (2)
    getNextPageParam: (lastPage) => lastPage.nextCursor,                           // (3)
  })

  if (query.isPending) return <p>Loading…</p>
  if (query.isError) return <p role="alert">{query.error.message}</p>

  return (
    <>
      <ul>
        {query.data.pages.flatMap((page) => page.items).map((item) => (            // (4)
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
      <button onClick={() => query.fetchNextPage()} disabled={!query.hasNextPage || query.isFetchingNextPage}>
        {query.isFetchingNextPage ? 'Loading…' : query.hasNextPage ? 'Load more' : 'No more products'}
      </button>
    </>
  )
}
  1. The value used for the first request. A cursor is a bookmark the server gives you that says "continue from here".
  2. The function receives pageParam, the value for this request.
  3. Given the last page that arrived, return the param for the next one, or null when there is nothing more. TanStack Query uses it to set hasNextPage.
  4. The data is a list of pages. We flatten them into one list of items. We tested with three pages of two items: after two clicks on "Load more", the list showed all six items and hasNextPage turned false.

10. Where each piece lives in a real project ​

PieceLocationWhy
QueryClient and the providermain.tsxone for the whole app
Key factories and queryOptionsapi/products.ts next to the fetch codethe key and the function stay together
useQuery callsIn the components that show the dataeach component asks for what it needs; the cache dedupes
Defaults (staleTime, retry)The QueryClient constructorone place to tune the whole app

Do not copy query data into useState "so you can change it". The cache already is the state. If you need the user's edits, keep only the edits in state and combine them when you draw. Changing server data itself goes through a mutation, which is the next page.

What the interviewer will push on ​

"Why use TanStack Query instead of useEffect and useState?" It owns caching, deduplication, background refetching, retry, cancellation and the loading and error states. Say the line that scores: "server state is a cache of data owned elsewhere, and hand-writing that is a source of race conditions". Then name two concrete things it does that the hand-written version does not (dedupe and stale-while-revalidate).

"What is a query key, and what goes into it?" The address of the data in the cache. Everything the query function depends on must be in it, so a changed input is a new entry. Mention key factories to prevent typos.

"Explain staleTime and gcTime." staleTime is how long data is trusted as fresh, so no refetch (default 0). gcTime is how long unused data stays in memory (default 5 minutes). The common wrong answer is to mix them up or to say that "stale means removed". Stale data is still shown.

"What is the difference between isPending, isLoading and isFetching?" isPending: no data yet. isFetching: a request is in flight (even when old data is on screen). isLoading: both pending and fetching. The distinction shows you know a query has two separate statuses.

"How do you avoid a loading flash when paging or filtering?" placeholderData: keepPreviousData.

"How do you make one query depend on another?" enabled.

"Does useQuery replace Redux?" For server data, yes. Client state such as a theme or a draft cart still needs useState, Context or a store. This is the five kinds of state table from page 6.4.6.

One thing to volunteer: say that you set staleTime per kind of data instead of leaving the default of 0 everywhere, and that you throw on non-OK responses in the query function because fetch does not.

Recall

  • Server state is a borrowed copy. TanStack Query caches it, shares it, and refreshes it.
  • Setup: one new QueryClient() for the app and <QueryClientProvider client={queryClient}> at the top.
  • useQuery({ queryKey, queryFn }) returns data, error, status, isPending, isError, isFetching, and more. The function must return a promise and must throw on failure (fetch does not throw on 404 and 500, so check res.ok). Pass signal to allow cancellation.
  • Key rule: everything the function uses goes in the key. Keys are hashed: object property order is ignored, array order matters. Use key factories and queryOptions.
  • Two timers: staleTime (trust as fresh, default 0) and gcTime (keep unused, default 5 min). Stale data is still shown while a refetch runs.
  • Two statuses: status (pending, error, success: do I have data?) and fetchStatus (fetching, idle, paused: is a request running?). v5: isPending is "no data yet"; isLoading is pending and fetching.
  • Refetches on mount, window focus and reconnect when stale; refetchInterval for polling. Retry defaults to 3 retries (4 calls).
  • Two components, same key = one request (deduplication).
  • enabled waits for a condition. placeholderData: keepPreviousData avoids loading flashes in paged lists. select reshapes the data for one component.
  • useInfiniteQuery with initialPageParam, getNextPageParam, fetchNextPage, hasNextPage. The data is pages.
  • Do not copy query data into useState.

Self-test: What two things does a key decide? · What is the difference between staleTime and gcTime? · Why can a query be success and fetching at the same time? · What happens if two components call useQuery with the same key? · Why does the query function have to throw on a 500 response?

Next: 6.4.11 covers changing data on the server: useMutation, telling the cache that something is out of date, and updating the screen before the server answers (optimistic updates).

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Volume I — Technology
Part 0 — Retention & Notation
Part 1 — Foundations of Computation
Part 2 — Operating Systems
2.1 The Kernel
2.2 Processes
2.3 Threads & Scheduling
2.4 Concurrency Under the Hood
2.5 Memory Management
2.6 File Systems
2.7 Input/Output
2.8 Linux for Engineers
2.9 Windows & macOS in Practice
Part 3 — Languages, Compilers & Runtimes
3.6 JavaScript & V8
3.7 TypeScript
3.8 Node.js Internals
3.13 Python & CPython
3.14 FastAPI & Production Python
Part 4 — Data Structures & Algorithms
4.0 Classic Problems — Before NeetCode
4.4 Arrays & Hashing — Problems
4.5 Two Pointers
4.6 Sliding Window
4.8 Stack — Problems
4.9 Linked List — Problems
4.11 Binary Search — Problems
4.13 Trees
4.14 Tree — Problems
4.15 Trie — Problems
4.17 Heap — Problems
4.18 Backtracking — Problems
4.19 Graphs
4.20 Graph — Problems
4.21 Advanced Graph — Problems
4.23 1-D DP — Problems
4.24 2-D DP — Problems
4.26 Greedy — Problems
4.27 Interval — Problems
4.28 Math & Geometry — Problems
4.30 Bit Manipulation — Problems
Part 5 — Networking & the Web
5.3 IP
5.4 Transport
5.6 HTTP
Part 6 — Frontend Engineering
6.1 Browser Internals
6.2 HTML & CSS Mastery
6.3 JavaScript in the Browser
6.4 React, from First Component to Full Shop
6.5 Frameworks & Rendering
6.8 UI Engineering & Patterns
Part 7 — Databases & Storage
7.2 SQL Mastery
7.3 Storage Engine Internals
7.4 Transactions
7.5 NoSQL Taxonomy
7.8 Analytics & Big Data
Part 8 — Security, Identity & Cryptography
8.2 Cryptography
8.3 Protocols of Trust
8.4 Identity: AuthN & AuthZ
8.5 Application Security
8.6 Infrastructure Security
Part 9 — Software Design (LLD)
9.2 OOP Foundations
9.3 Design Principles
9.4 Design Patterns
9.5 Concurrency
9.6 API Design
9.7 LLD Interview Machines
9.9 Node/Express Production Playbook
Part 10 — Distributed Systems & HLD
10.7 Consistency & Consensus
10.8 Messaging & Microservices
10.14 Caching
Building blocks from the design seat
Part 11 — System Design Case Studies
Part 12 — AI & ML Engineering
12.1 What AI Engineering Is
12.2 The Math You Need
12.3 Classical Machine Learning
12.4 Data for ML
12.5 Deep Learning
12.6 Embeddings & Vector Search
12.7 Transformers & LLMs
12.8 Building with LLMs
12.9 Retrieval-Augmented Generation
12.10 Agents
12.11 Adapting Models
12.12 Production AI
12.13 Multimodal AI
12.14 AI Security & Governance
12.15 Case Studies & Capstone
Part 13 — Cloud, DevOps & Infrastructure
13.11 Git, from First Commit to Team Workflow
Part 14 — Containers: Docker & Kubernetes
14.1 Foundations
14.2 Docker
14.3 Kubernetes
14.4 Kubernetes on Azure
Part 15 — The Craft & Career
Nothing picked yet