Sub topic 11
Fetching with TanStack Query
This chapter assumes you can write a component that fetches data in useEffect with loading and error state, and that you know why that code needs AbortController cleanup. You should also be comfortable with promises, async/await, and the useState hook. The chapter covers what TanStack Query is, how to set it up, how useQuery replaces the manual code, and the mistakes people make most often.
Why a library at all
In the previous chapter you saw where effect-based fetching falls short. Each component keeps its own copy of the data. Two components that need the same user send two requests. Nothing remembers a result after the component unmounts. Nothing refetches when the user returns to the tab. You could build all of that yourself, but it takes a lot of code, and the edge cases are easy to get wrong.
TanStack Query (formerly React Query) is a server-state library. Server state is data that lives on a server, that you only hold a copy of, and that can change without your app knowing. TanStack Query keeps those copies in a cache outside your components. Components subscribe to cache entries and re-render when an entry changes.
Compare the two models:
| Concern | Fetching in `useEffect` | TanStack Query |
|---|---|---|
| Where data lives | Component state | Shared cache |
| Duplicate requests | One per component | Deduplicated by key |
| Cancellation | You write the cleanup | Library passes a `signal` |
| Refetching | You write it | Built in (focus, reconnect, invalidation) |
| Retries | You write them | Built in, three retries by default |
| Reuse after unmount | None | Cached data can be reused |
Setting up
Install the package:
npm install @tanstack/react-queryCreate one QueryClient, which owns the cache, and make it available with QueryClientProvider. Create the client once, outside any component, or keep it in a stable place such as useState. If you create it inside a component body, every render produces a fresh, empty cache.
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { createRoot } from 'react-dom/client';
const queryClient = new QueryClient();
function UserProfile({ userId }) {
return <p>User {userId}</p>;
}
createRoot(document.getElementById('root')).render(
<QueryClientProvider client={queryClient}>
<UserProfile userId={1} />
</QueryClientProvider>
);Reading data with useQuery
Here is the component from the effect-based chapters, rewritten with useQuery:
import { useQuery } from '@tanstack/react-query';
async function fetchUser(userId, signal) {
const response = await fetch(`/api/users/${userId}`, { signal });
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
}
function UserProfile({ userId }) {
const { data, error, isPending } = useQuery({
queryKey: ['user', userId],
queryFn: ({ signal }) => fetchUser(userId, signal),
});
if (isPending) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return <h1>{data.name}</h1>;
}Three pieces matter here.
queryKeyis an array that identifies the data. Two components that use['user', 1]share one cache entry and one request.queryFnis a function that returns a promise. It receives a context object that includes anAbortSignal. If every observer of the query unmounts while the request is in flight, the library can abort it, as long as you pass thesignaltofetch.- The result object carries the request state. You no longer declare
useStatefordata,error, and loading.
The query function must throw on failure
TanStack Query decides that a query failed only when the promise rejects. fetch does not reject on a 404 or 500, so the response.ok check is still your job. Without it, an error page body would be cached as if it were a valid user. This is the single most common bug in first-time setups.
The state flags
The result object describes two separate things: the status of the data and the status of the fetch.
| Field | Meaning |
|---|---|
| `status` | `'pending'` (no data yet), `'error'`, or `'success'` |
| `fetchStatus` | `'fetching'`, `'paused'` (offline), or `'idle'` |
| `isPending` | No data in the cache yet |
| `isFetching` | A request is in flight, including background refetches |
| `isLoading` | `isFetching && isPending`: the first load only |
These are independent. A query with cached data can be success and fetching at once, which means it is refreshing in the background. Use isPending to decide whether you have anything to show. Use isFetching to show a small refresh indicator.
The Refetching state in the diagram is not a separate status. It is status: 'success' with fetchStatus: 'fetching'.
What the library does for you
Compared with the effect version, useQuery handles these cases without extra code:
- Race conditions. Each key has its own cache entry. When
userIdchanges, the component subscribes to a different entry, so a late response for the old id cannot overwrite the new one. - Deduplication. If three components mount with the same key at once, one request goes out.
- Retries. A failed query retries up to three times with exponential backoff before it reports an error. Retries delay the error state, so a failing endpoint can look like a long load. Lower
retryin tests and for requests where a failure is final, such as a 404. - Background refetching. Queries refetch when the window regains focus, when the network reconnects, and when a new component mounts with stale data.
Common errors
Missing variables in the key. Everything the queryFn reads from props or state must appear in queryKey. If userId is used in the function but left out of the key, changing userId shows the old user's data, because the key did not change.
Unstable keys. Keys are compared by value, so ['user', 1] equals ['user', 1] across renders. Objects in keys are also compared by content with stable property ordering. Mixing types is a real problem, though: ['user', 1] and ['user', '1'] are different entries.
Copying query data into state. Writing useEffect(() => setUser(data), [data]) creates a second source of truth that lags one render behind. Read data directly, or derive values from it during render.
Treating data as always defined. While isPending is true, data is undefined. Check the status first, as the example does, or data.name throws.
Expecting errors to appear immediately. With default retries, the first failure is not reported until three more attempts fail. That is expected behavior, not a hang.
Useful options
Pass these to useQuery when the defaults do not fit:
import { useQuery } from '@tanstack/react-query';
async function fetchUser(userId, signal) {
const response = await fetch(`/api/users/${userId}`, { signal });
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
}
function UserName({ userId }) {
const { data, isPending, isFetching } = useQuery({
queryKey: ['user', userId],
queryFn: ({ signal }) => fetchUser(userId, signal),
enabled: userId != null,
retry: 1,
});
if (isPending) return <p>Loading...</p>;
return (
<h1>
{data.name} {isFetching ? '(refreshing)' : ''}
</h1>
);
}enabled: false stops the query from running, which is how you express a dependent query such as "fetch the user only after the id is known". Note that a disabled query with no cached data stays in pending, so isPending alone cannot distinguish "loading" from "waiting". In that case use isLoading, which is false when nothing is fetching.
Exercise
A component calls useQuery with queryKey ['user'] and a queryFn that fetches /api/users/${userId}. When the userId prop changes from 1 to 2, the component keeps showing user 1. What is wrong, and how do you fix it? Also, the endpoint returns a 500 page with an HTML body and the component shows a broken user instead of an error. What is missing?
Show answer
The key does not include userId, so both ids share one cache entry and the key never changes. Fix it with queryKey: ['user', userId]. For the 500 case, the queryFn does not check response.ok. fetch resolves on HTTP error statuses, so the query succeeds with the wrong body. Throw an Error when !response.ok so the promise rejects and the query enters the error state.
Exercise
A query has cached data and the window regains focus, triggering a refetch. What are status, isPending, and isFetching while the request is in flight?
Show answer
status is 'success' and isPending is false, because cached data exists. isFetching is true because a request is in flight. The user keeps seeing the cached data while the refresh runs.