TanStack Query

Topic 3 of 4 in Data fetching7 min readIntermediateFree course

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

Terminal
npm install @tanstack/react-query
JSX
// 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

JSX
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:

CourseList and Sidebar both call useQuery with the key [‘courses’]; one request fills the query cache and is shared by both. Data moves through states: fetching on first load, fresh and served from cache, stale after staleTime, then refetched in the background. Stale data is shown instantly while fresh data loads. Refetches happen on window focus, remount and reconnect.

  • 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:

JSX
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:

JavaScript
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:

JSX
useQuery({ ...courseQueries.all(), staleTime: 5 * 60 * 1000 }); // fresh for 5 minutes

You can set defaults for the whole app:

JSX
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:

JSX
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:

JSX
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:

JSX
function CourseHeader({ id }) {
  const { data: course } = useSuspenseQuery(courseQueries.detail(id));
  return <h1>{course.title}</h1>;
}

<Suspense fallback={<HeaderSkeleton />}>
  <CourseHeader id={id} />
</Suspense>

Devtools

Terminal
npm install -D @tanstack/react-query-devtools
JSX
import { 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.

Exercise

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.

JavaScript
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
}

Summary

  • Server state is a cache of data owned by the server; TanStack Query manages fetching, caching and refreshing it.
  • useQuery({ queryKey, queryFn }) returns data, isPending, isError, error and isFetching.
  • The query key identifies the data; include every variable the query depends on.
  • Cached data is shown instantly; staleTime controls when it’s refetched in the background.
  • Requests are deduplicated, retried on failure and refetched on window focus and reconnect.