TanStack Query
Overview
Data from a server is different from local UI state. It’s owned by someone else, it can change without you knowing, many components need it, and you want to avoid fetching it again and again. Managing that well — caching, deduplicating, refreshing, retrying — is a lot of work. TanStack Query (formerly React Query) does it for you, and it’s the most widely used data-fetching library in React.
Setup
npm install @tanstack/react-query// main.jsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient();
createRoot(document.getElementById('root')).render(
<StrictMode>
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</StrictMode>,
);The QueryClient holds the cache. Create it once, outside your components.
Your first query
import { useQuery } from '@tanstack/react-query';
async function fetchCourses() {
const res = await fetch('/api/courses');
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
return res.json();
}
function CourseList() {
const { data, isPending, isError, error } = useQuery({
queryKey: ['courses'],
queryFn: fetchCourses,
});
if (isPending) return <Spinner />;
if (isError) return <p role="alert">{error.message}</p>;
return <ul>{data.map((c) => <li key={c.id}>{c.title}</li>)}</ul>;
}Compare this with the effect version from Fetching data: no useState, no useEffect, no race conditions, no cleanup. And you get much more:
- Caching: leave the page and come back — the list appears instantly from the cache.
- Deduplication: ten components using
['courses']share one request. - Background refetching: when the window regains focus or the network reconnects, stale data is refreshed quietly.
- Retries: failed requests are retried three times with backoff before showing an error.
Query keys
The query key is an array that uniquely identifies the data. Include every variable the query depends on:
function CourseDetail({ id }) {
const { data: course } = useQuery({
queryKey: ['courses', id],
queryFn: () => fetchJson(`/api/courses/${id}`),
});
}
function SearchResults({ q, level }) {
const { data } = useQuery({
queryKey: ['courses', { q, level }],
queryFn: () => fetchJson(`/api/courses?${new URLSearchParams({ q, level })}`),
});
}When id changes, the key changes, and TanStack Query fetches (or reads from cache) the new data automatically — no dependency arrays to maintain. Keys are hierarchical, which matters later for invalidation: ['courses'] is a prefix of ['courses', 7].
A common practice is to keep keys and fetchers together:
export const courseQueries = {
all: () => ({ queryKey: ['courses'], queryFn: () => fetchJson('/api/courses') }),
detail: (id) => ({ queryKey: ['courses', id], queryFn: () => fetchJson(`/api/courses/${id}`) }),
};
// useQuery(courseQueries.detail(id))Status flags
| Flag | Meaning |
|---|---|
isPending |
no data yet (first load) |
isError / error |
the query failed after retries |
isSuccess / data |
data is available |
isFetching |
a request is in flight — including background refetches |
isPlaceholderData |
showing placeholder (e.g. the previous page) |
Use isPending for the first-load spinner and isFetching for a subtle “updating” indicator.
Fresh and stale
Every cached result is either fresh or stale:
- Fresh data is served from the cache without a request.
- Stale data is still shown immediately, but TanStack Query refetches it in the background when a component mounts, the window is focused, or the network reconnects.
By default, data becomes stale immediately (staleTime: 0), which favours freshness. For data that rarely changes, raise it:
useQuery({ ...courseQueries.all(), staleTime: 5 * 60 * 1000 }); // fresh for 5 minutesYou can set defaults for the whole app:
const queryClient = new QueryClient({
defaultOptions: { queries: { staleTime: 60_000 } },
});Unused data is removed from the cache after gcTime (5 minutes by default).
Dependent queries
When one query needs another’s result, disable it until the input exists with enabled:
const { data: user } = useQuery({ queryKey: ['me'], queryFn: fetchMe });
const { data: enrolments } = useQuery({
queryKey: ['enrolments', user?.id],
queryFn: () => fetchJson(`/api/users/${user.id}/enrolments`),
enabled: !!user,
});Pagination
Keep the previous page on screen while the next one loads, instead of flashing a spinner:
import { keepPreviousData } from '@tanstack/react-query';
const { data, isPlaceholderData } = useQuery({
queryKey: ['courses', { page }],
queryFn: () => fetchCourses(page),
placeholderData: keepPreviousData,
});For “load more” and infinite scrolling, use useInfiniteQuery.
Suspense mode
If you prefer Suspense boundaries for loading states, useSuspenseQuery suspends instead of returning isPending, and data is always defined:
function CourseHeader({ id }) {
const { data: course } = useSuspenseQuery(courseQueries.detail(id));
return <h1>{course.title}</h1>;
}
<Suspense fallback={<HeaderSkeleton />}>
<CourseHeader id={id} />
</Suspense>Devtools
npm install -D @tanstack/react-query-devtoolsimport { ReactQueryDevtools } from '@tanstack/react-query-devtools';
<QueryClientProvider client={queryClient}>
<App />
<ReactQueryDevtools />
</QueryClientProvider>A floating panel shows every query, its key, status and data — invaluable for understanding cache behaviour. It’s excluded from production builds automatically.
Server state vs client state
TanStack Query is for server state. Keep using useState, context or a store for client state — which tab is open, form drafts, the theme. Moving server data into TanStack Query usually shrinks global state dramatically.
Next: reading data is half the story. The next lesson covers changing it — mutations, cache invalidation and optimistic updates.
A searchable, paginated course list
Using TanStack Query, write useCourses({ q, page }) that fetches /api/courses?q=…&page=… with the query key ['courses', { q, page }], a staleTime of 60 seconds and placeholderData: keepPreviousData so the old page stays visible while the next loads. Build CourseList with a search input, “Previous”/“Next” buttons and an “Updating…” label shown while a background fetch is running.
import { useState } from 'react';
import { useQuery, keepPreviousData } from '@tanstack/react-query';
export function useCourses({ q, page }) {
// your code here
}
export function CourseList() {
// your code here
}import { useState } from 'react';
import { useQuery, keepPreviousData } from '@tanstack/react-query';
async function fetchCourses({ q, page }) {
const params = new URLSearchParams({ q, page: String(page) });
const res = await fetch(`/api/courses?${params}`);
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
return res.json(); // { items: [...], hasMore: boolean }
}
export function useCourses({ q, page }) {
return useQuery({
queryKey: ['courses', { q, page }],
queryFn: () => fetchCourses({ q, page }),
staleTime: 60_000,
placeholderData: keepPreviousData,
});
}
export function CourseList() {
const [q, setQ] = useState('');
const [page, setPage] = useState(1);
const { data, isPending, isError, error, isFetching, isPlaceholderData } = useCourses({ q, page });
return (
<section>
<input
aria-label="Search"
value={q}
onChange={(e) => {
setQ(e.target.value);
setPage(1);
}}
/>
{isFetching && <span>Updating…</span>}
{isPending ? (
<p>Loading…</p>
) : isError ? (
<p role="alert">{error.message}</p>
) : (
<ul>
{data.items.map((c) => <li key={c.id}>{c.title}</li>)}
</ul>
)}
<button disabled={page === 1} onClick={() => setPage((p) => p - 1)}>Previous</button>
<span>Page {page}</span>
<button
disabled={isPlaceholderData || !data?.hasMore}
onClick={() => setPage((p) => p + 1)}
>
Next
</button>
</section>
);
}Summary
- Server state is a cache of data owned by the server; TanStack Query manages fetching, caching and refreshing it.
useQuery({ queryKey, queryFn })returnsdata,isPending,isError,errorandisFetching.- The query key identifies the data; include every variable the query depends on.
- Cached data is shown instantly;
staleTimecontrols when it’s refetched in the background. - Requests are deduplicated, retried on failure and refetched on window focus and reconnect.