Appearance
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.
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-querytsx
// 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>,
)- 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.
QueryClientProvidermakes it available to all components below, through Context. This is the same idea as the ReduxProvideron 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
}signalis optional. It lets the library cancel the request if the component goes away or the key changes. (The browser'sAbortSignalis the standard way to cancel afetch.)fetchdoes 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>
)
}queryKeyis the address of this data in the cache. It is an array. Here it is just['products'].queryFnis the function that fetches the data. It must return a promise. Whatever it resolves to is the data. TypeScript works out the type ofquery.datafrom it.isPendingistruewhile there is no data yet for this key. This is the "waiting" situation from the three-state figure on page 6.4.3.isErroristruewhen the function threw (after the retries, which come soon).query.errorholds the error.- By the time we reach this line, TypeScript knows the query succeeded, because both early returns are above it. So
query.datais aProduct[], notProduct[] | 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),
})- 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),
})allis 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 consttells TypeScript the array has exactly these items, in this order.queryOptionsis a small helper that bundles a key with its function. Anywhere you need this query, you writeuseQuery(productListOptions('kitchen')). The key and the function can no longer drift apart. And the same bundle can be used in a router loader or inqueryClient.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.
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 is | Example | staleTime |
|---|---|---|
| Changes constantly | stock levels, a live score | 0 (default) |
| Changes now and then | product list, user's orders | 30 seconds to a few minutes |
| Almost never changes | country list, settings | 10 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.
| Field | Answers the question | Values |
|---|---|---|
status | Do I have data? | 'pending' (no), 'error' (it failed), 'success' (yes) |
fetchStatus | Is 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 to | Use |
|---|---|
| Show a full-page loader for the very first load | isPending |
| Show a small "refreshing…" spinner while old data stays visible | isFetching && !isPending |
| Show an error | isError (and error) |
| Know whether the data on screen is a stand-in | isPlaceholderData (section 8) |
7. When does it fetch again?
By default, a stale query refetches when:
- A component using it mounts (appears on the screen).
- The browser window regains focus. The user comes back from another tab and sees fresh data, with no code from you.
- The network reconnects.
- You call
refetch(), or you invalidate it (next page). - A timer, if you ask for one:
refetchInterval: 10_000refetches 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)
})keepPreviousDatasays "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 withisPlaceholderDataset totrue. When page 2 arrived, it was replaced. You can useisPlaceholderDatato 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>
</>
)
}- The value used for the first request. A cursor is a bookmark the server gives you that says "continue from here".
- The function receives
pageParam, the value for this request. - Given the last page that arrived, return the param for the next one, or
nullwhen there is nothing more. TanStack Query uses it to sethasNextPage. - 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
hasNextPageturnedfalse.
10. Where each piece lives in a real project
| Piece | Location | Why |
|---|---|---|
QueryClient and the provider | main.tsx | one for the whole app |
Key factories and queryOptions | api/products.ts next to the fetch code | the key and the function stay together |
useQuery calls | In the components that show the data | each component asks for what it needs; the cache dedupes |
Defaults (staleTime, retry) | The QueryClient constructor | one 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 })returnsdata,error,status,isPending,isError,isFetching, and more. The function must return a promise and must throw on failure (fetchdoes not throw on 404 and 500, so checkres.ok). Passsignalto 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) andgcTime(keep unused, default 5 min). Stale data is still shown while a refetch runs. - Two statuses:
status(pending, error, success: do I have data?) andfetchStatus(fetching, idle, paused: is a request running?). v5:isPendingis "no data yet";isLoadingis pending and fetching. - Refetches on mount, window focus and reconnect when stale;
refetchIntervalfor polling. Retry defaults to 3 retries (4 calls). - Two components, same key = one request (deduplication).
enabledwaits for a condition.placeholderData: keepPreviousDataavoids loading flashes in paged lists.selectreshapes the data for one component.useInfiniteQuerywithinitialPageParam,getNextPageParam,fetchNextPage,hasNextPage. The data ispages.- 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).