Sub topic 11
Fetching with TanStack Query
This chapter assumes you know useState, useEffect, promises and async/await, and how to check response.ok with fetch. You have already written loading, error, and success states by hand. Here you replace that code with a library.
Why use a server-state library
Data from a server is different from UI state like "is this menu open". The server owns it, it can change without your app knowing, and many components may need the same copy. Effect-based fetching leaves you to handle caching, sharing, and refetching yourself.
TanStack Query is a server-state library. You describe what to fetch and give it a name. The library runs the request, tracks its status, caches the result, and cancels or ignores outdated requests.
Install it and wrap your app in a provider:
npm install @tanstack/react-queryimport { QueryClient, QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient();
export function App({ children }) {
return (
<QueryClientProvider client={queryClient}>
{children}
</QueryClientProvider>
);
}Create the QueryClient once, outside any component. The client holds the cache, and a new client on every render would discard it.
Reading data with useQuery
useQuery takes two required options:
queryKey: an array that identifies the data. Equal keys share one cache entry.queryFn: a function that returns a promise of the data.
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>;
}Compare this with the hand-written version. There is no useEffect, no three useState calls, and no cleanup function. The library gives you isPending, error, and data.
Two details matter:
- The function must throw on failure.
fetchonly rejects on network failure, so you still checkresponse.okand throw. TanStack Query treats a rejected promise as an error and does not look at HTTP status codes. - Pass
signalalong. The library givesqueryFnanAbortSignal. When you pass it tofetch, the request is cancelled if the component unmounts or the key changes while the request is in flight.
Keys drive refetching
Include every value the query function uses in the key, as you would in a dependency array. When userId changes from 1 to 2, the key changes from ['user', 1] to ['user', 2]. The library treats that as a different query and fetches it. Responses are stored per key, so a slow response for user 1 cannot overwrite user 2. This removes the race condition you handled by hand earlier.
Common errors
- Missing a variable in the key. If
queryFnusesuserIdbut the key is['user'], every user shares one cache entry and you see the wrong data. - Forgetting to throw on non-2xx responses. A 404 body is then treated as successful data.
- Creating the
QueryClientinside a component. The cache resets on re-render. - Using
isLoadingandisPendinginterchangeably.isPendingmeans there is no data yet. Use it to guarddata.name.
Exercise
A component calls useQuery with queryKey ['user'] and a queryFn that fetches /api/users/${userId}. The userId prop changes from 1 to 2, but the screen still shows user 1. Why, and how do you fix it?
Show answer
The key does not include userId, so both ids map to the same cache entry and the library has no reason to refetch. Change the key to ['user', userId] so each id gets its own entry and a change triggers a new fetch.
Exercise
Your queryFn calls fetch and returns response.json() without checking response.ok. The server returns a 500 with a JSON error body. What does the component show, and why?
Show answer
It shows the success state with the error body as data. fetch resolves for HTTP error statuses, so the promise does not reject and TanStack Query sees no error. Check response.ok and throw an Error in queryFn.