Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 132 ยท Data and Async

TanStack Query in Depth

Learn TanStack Query (React Query) in depth - query keys, staleTime and gcTime, dedupe, mutations, invalidation and optimistic updates with rollback, plus runnable stand-ins for the editor.

If you fetch data with useEffect, you soon rewrite the same code again and again: a loading flag, an error flag, a cancelled flag for races, a cache so that going back to a page is instant, a refetch when the data changes, a way to share one request between components. The earlier lessons showed how to do it by hand in fetching data, async patterns and caching and server state. TanStack Query (formerly React Query) is the most popular library that does all of this for you.

Its core idea is the one from the state management lesson: server state is different from client state. The data lives on a server, you only hold a copy, and the copy goes stale. TanStack Query manages that copy: it fetches, caches, de-duplicates, refetches and updates it, so your components just ask for data. This lesson covers queries, cache freshness, mutations, invalidation and optimistic updates.

TanStack Query is an npm package (@tanstack/react-query), which our editor cannot load. Code that imports it is shown read-only and uses the v5 API. To let you experiment, the runnable examples use a roughly forty-line stand-in with the same shape. The stand-in teaches the ideas; it is not a replacement for the real library, which also handles retries, garbage collection, request cancellation, focus refetching, pagination and much more.

Setup and your first query

You create one QueryClient, which owns the cache, and make it available with a provider. Then any component can call useQuery.

JSX
// needs @tanstack/react-query
import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query';

const queryClient = new QueryClient();

async function fetchTodos() {
  const response = await fetch('/api/todos');
  if (!response.ok) throw new Error('Request failed: ' + response.status);
  return response.json();
}

function Todos() {
  const { data, isPending, isError, error, isFetching } = useQuery({
    queryKey: ['todos'],
    queryFn: fetchTodos,
  });

  if (isPending) return <p>Loading...</p>;
  if (isError) return <p>Something went wrong: {error.message}</p>;
  return (
    <ul>
      {data.map((todo) => <li key={todo.id}>{todo.title}</li>)}
      {isFetching && <li>Refreshing...</li>}
    </ul>
  );
}

// <QueryClientProvider client={queryClient}><Todos /></QueryClientProvider>

A query has two required parts:

  • queryKey: an array that identifies the data. It is the cache key and the dependency list. Include every value the function uses, such as ['todo', id] or ['todos', { status: 'done' }]. A different key is a different cache entry, and React Query fetches it on its own.
  • queryFn: an async function that returns the data, or throws. A failed fetch does not throw on HTTP errors by itself, so check response.ok as above.

The result tells you where you are. isPending means there is no data yet; isError means the request failed (after retries, three by default with growing delays); isFetching is true whenever a request is in flight, including background refreshes when you already have data. Distinguishing "no data yet" from "refreshing" is the main reason this API is nicer than a single loading boolean.

Fresh, stale and garbage-collected

Two timers control the cache, and mixing them up is the most common source of confusion.

  • staleTime (default 0): how long data counts as fresh after a fetch. Fresh data is served from the cache with no network request. Stale data is still shown instantly, but the library refetches it in the background when something triggers a check: a component mounts, the window regains focus, the network reconnects, or you invalidate it. This is the stale-while-revalidate strategy.
  • gcTime (default 5 minutes): how long data stays in memory after the last component using it unmounted. Then it is garbage-collected and the next use shows isPending again.
stateDiagram-v2
    [*] --> Fetching: first use
    Fetching --> Fresh: data arrives
    Fresh --> Stale: staleTime passes
    Stale --> Fetching: mount, focus, reconnect or invalidate
    Fresh --> Inactive: no component uses it
    Stale --> Inactive: no component uses it
    Inactive --> Fetching: used again
    Inactive --> [*]: gcTime passes

A cache entry's life. "Stale" does not mean "bad": the data is shown at once while a refresh runs in the background.

With the default staleTime of 0, data is immediately stale, so every mount triggers a background refetch. Many apps set a longer staleTime globally (for example 30 seconds) and a shorter one for fast-changing data.

A runnable stand-in

The stand-in below is a tiny cache with the same ideas: a key to entry map, de-duplication of in-flight requests, staleTime, a status, isFetching, and invalidateQueries. A fake server answers after 400 ms and logs each request, so you can count the network calls. It uses the useSyncExternalStore recipe from external stores.

A mini cache: dedupe, freshness and invalidation

Look at the console on load: one GET /todos, although two components asked for the same key. The second caller found a request in flight and shared it. Both lists show "pending", then the same two todos.

Now click "Someone else adds a todo". The console confirms the server changed, but the screen does not, because the cached data is still fresh for 30 seconds. Click "Invalidate": the status line shows (refreshing...) for 400 ms while the old list stays visible, then both lists update from a single second request. That is invalidation, and it is the tool you will use most after a mutation.

Query keys are a hierarchy

Real query keys are arrays, and invalidation matches by prefix. With keys like ['todos'], ['todos', 'list', { status: 'done' }] and ['todos', 'detail', 7], calling invalidateQueries({ queryKey: ['todos'] }) marks all of them stale and refetches the ones that are on screen. A more specific call, like invalidateQueries({ queryKey: ['todos', 'detail', 7] }), touches one entry. Design your keys like URLs: general to specific. A common habit is a small "key factory" object, so keys are never typed by hand in two places.

Other options you will meet in the docs, all read-only here:

JSX
useQuery({
  queryKey: ['todo', id],
  queryFn: () => fetchTodo(id),
  enabled: id != null,                 // do not run until we have an id
  select: (todo) => todo.title,        // derive a slice; re-renders only when it changes
  placeholderData: (previous) => previous, // keep the old data while a new key loads
  retry: 1,                            // default is 3 with exponential backoff
  refetchOnWindowFocus: false,         // default is true
});

enabled handles dependent queries, placeholderData avoids a spinner flash while paging through results, and useInfiniteQuery and useQueries handle "load more" lists and many queries at once. Because loading and error states are all in the return value, you can combine the library with Suspense and error boundaries through its useSuspenseQuery hook and the throwOnError option.

Mutations

A query reads data. A mutation changes data on the server: create, update, delete. It does not run automatically; you call mutate(variables) from an event handler.

JSX
function AddTodo() {
  const queryClient = useQueryClient();
  const addTodo = useMutation({
    mutationFn: (title) =>
      fetch('/api/todos', { method: 'POST', body: JSON.stringify({ title }) }).then((r) => r.json()),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['todos'] });
    },
  });

  return (
    <button disabled={addTodo.isPending} onClick={() => addTodo.mutate('Write a lesson')}>
      {addTodo.isPending ? 'Saving...' : 'Add todo'}
    </button>
  );
}

A mutation has its own state (isPending, isError, isSuccess, data, error, variables) and lifecycle callbacks: onMutate (before the request), onSuccess, onError and onSettled (after either outcome). The standard recipe is: mutate, then invalidate the queries that the change affects, so the cache is refetched from the single source of truth. That is correct and simple, with one cost: the user waits for two round trips before the screen shows the result.

Optimistic updates

If success is the usual outcome, you can update the screen before the server answers, and undo it if the request fails. The pattern has four steps: save the current cache value, write the expected new value, roll back on error, and refetch at the end to be sure.

sequenceDiagram
    participant U as User
    participant C as Cache and UI
    participant S as Server
    U->>C: click "done"
    C->>C: onMutate: save snapshot, write new value
    C->>S: PATCH request
    alt success
        S-->>C: 200 OK
    else failure
        S-->>C: error
        C->>C: onError: restore the snapshot
    end
    C->>S: onSettled: invalidate and refetch
    S-->>C: truth from the server

An optimistic update shows the result at once, then lets the server have the final word.

The real code follows those steps. Note cancelQueries, which stops a background refetch from overwriting your optimistic value while the mutation is in flight:

JSX
const toggleTodo = useMutation({
  mutationFn: (id) => fetch('/api/todos/' + id + '/toggle', { method: 'PATCH' }),
  onMutate: async (id) => {
    await queryClient.cancelQueries({ queryKey: ['todos'] });
    const previous = queryClient.getQueryData(['todos']);
    queryClient.setQueryData(['todos'], (old) =>
      old.map((todo) => (todo.id === id ? { ...todo, done: !todo.done } : todo))
    );
    return { previous };                       // becomes `context`
  },
  onError: (error, id, context) => {
    queryClient.setQueryData(['todos'], context.previous);
  },
  onSettled: () => {
    queryClient.invalidateQueries({ queryKey: ['todos'] });
  },
});

Here is the same flow running with the stand-in. A checkbox makes the next save fail so you can watch the rollback. The fake server takes 600 ms.

Optimistic update with rollback

Tick a todo with the failure box off: it is struck through immediately, 600 ms later the console prints network: PATCH /todos/1 saved, and a refetch follows. Now tick the failure box and click the other todo: it flips at once, and about half a second later the console prints rollback: todo 2 restored (Server said no) and the checkbox jumps back. The user sees instant feedback in the common case and an honest correction in the rare one.

Optimistic updates are not free: you must handle failures, avoid races between several quick clicks (that is what cancelQueries and per-item mutation keys are for), and keep the cache shape in your head. For many forms the simpler variables approach is enough: while isPending, render the pending item from mutation.variables as a greyed row, with no cache writes at all. React 19's useOptimistic offers the same idea inside the component tree.

When to use it, and when not

Use TanStack Query when your app talks to many endpoints, shows the same data in several places, or needs caching, refetching and consistent loading states. Skip it for a tiny page with one request, or if your framework already provides a data layer (server components and loaders cover much of the same ground). Whatever you choose, keep server data in one tool and client state in useState or a small store; copying query results into useState defeats the cache. For tests, see testing React components: create a fresh QueryClient per test, with retries turned off.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does staleTime control?

    While data is fresh it is served from the cache without a network request. How long unused data stays in memory is gcTime, and retries are controlled by retry.
  2. 2. Two components mounted at the same time call useQuery with the same key. How many network requests are made?

    Requests for the same key are de-duplicated, and every component subscribed to the key receives the result.
  3. 3. After a mutation succeeds, what is the standard way to make lists on the screen show the new server state?

    Invalidation marks the cached data stale and refetches the queries that are on screen, so they show what the server now holds.
  4. 4. In an optimistic update, what is onError for?

    onMutate writes the expected result and returns the previous data as context; onError uses that context to put the old data back.
  5. 5. Which query key lets invalidateQueries({ queryKey: ['todos'] }) also refresh the entry for ['todos', 'detail', 7]?

    Query keys are hierarchical arrays, and a partial key matches every entry that starts with it.

Summary

  • TanStack Query manages server state: it fetches, caches, de-duplicates and refreshes the copy of remote data that your components use.
  • A query is identified by its queryKey (an array that includes everything the queryFn depends on). isPending means no data yet; isFetching includes background refreshes.
  • staleTime decides how long data is fresh; gcTime decides how long unused data stays in memory. Stale data is shown at once and refetched in the background.
  • A mutation changes server data. After it, invalidate the affected keys (prefix matching) so queries refetch.
  • Optimistic updates write the expected result in onMutate, restore a snapshot in onError, and invalidate in onSettled. Use them when instant feedback matters and failure is rare.
  • The editor cannot load the package, so the examples here used a small stand-in; install the real library in your own project.

Next: Rendering in Depth