Server state

TanStack Query, SWR and RTK Query: caching data you don't own.

Builds on Kinds of state, Suspense and use.

The list of books in the reading list doesn't belong to your app. It lives in a database on a server, other people change it, and what you have in the browser is a copy that starts going out of date the moment it arrives. That's server state, and it behaves nothing like the client state the last few chapters stored in Redux, Zustand, Jotai or MobX.

Kinds of state named the category. Suspense and use showed how to wait for data. This chapter is about keeping it: caching it, sharing it between components, deciding when it's too old, refetching it, and updating it after a mutation. The one-sentence version, which is also the interview answer: server state is a cache, not state you own. Libraries like TanStack Query and SWR are cache managers, and once you see them that way their options stop looking arbitrary.

The problem: fetching in effects#

Here's how most apps start. Two components need the books, so each fetches them in an effect.

Each component fetches for itself
import { useEffect, useState } from "react";
import { fakeFetch } from "guide-tools";

type Book = { id: number; title: string };
let requests = 0;

function useBooks() {
  const [books, setBooks] = useState<Book[] | null>(null);
  useEffect(() => {
    let ignore = false;
    console.log(`request #${++requests}`);
    fakeFetch("/books", { delay: 700 }).then((data) => !ignore && setBooks(data));
    return () => {
      ignore = true;
    };
  }, []);
  return books;
}

function BookCount() {
  const books = useBooks();
  return <p>{books ? `${books.length} books` : "Loading count..."}</p>;
}

function BookList() {
  const books = useBooks();
  if (!books) return <p>Loading list...</p>;
  return (
    <ul>
      {books.slice(0, 4).map((b) => (
        <li key={b.id}>{b.title}</li>
      ))}
    </ul>
  );
}

export default function App() {
  const [showList, setShowList] = useState(true);
  return (
    <>
      <button onClick={() => setShowList((s) => !s)}>{showList ? "Hide" : "Show"} list</button>
      <BookCount />
      {showList && <BookList />}
    </>
  );
}
Nothing logged yet.

Two components, two identical requests. Hide and show the list: a third request, and a loading flash for data you had a second ago. And this version already handles the race condition with ignore; plenty of real code doesn't. Now imagine the user adds a book: who tells both components their copy is out of date?

Moving the data into a global store fixes the duplicate request, and then you hand-write isLoading, error, "fetched at", "is a request already running", refetch-on-focus and invalidation for every endpoint. That's not state management. That's writing a cache, badly, once per endpoint.

What you actually need, for each piece of server data:

  1. One copy per resource, keyed by what identifies it, shared by every component that asks.
  2. Deduplication: concurrent requests for the same key share one promise.
  3. A freshness policy: how long data counts as fresh before it may be refetched.
  4. Refetch triggers: when to check the server again.
  5. Invalidation: after a mutation, mark related data as out of date.
  6. Garbage collection: drop data nobody has used for a while.

Build it: a query cache in 50 lines#

The first four fit in a small module. It's the toy store from Build a store with one entry per key, a promise for deduplication, and a timestamp for freshness.

A toy query cache
import { useState } from "react";
import { fakeFetch } from "guide-tools";
import { useQuery, invalidate } from "./queryCache";

type Book = { id: number; title: string };
let requests = 0;
const getBooks = () => {
  console.log(`request #${++requests}`);
  return fakeFetch("/books", { delay: 700 }) as Promise<Book[]>;
};

function BookCount() {
  const { data, isFetching } = useQuery("books", getBooks, { staleTime: 5000 });
  return <p>{data ? `${data.length} books` : "Loading count..."} {isFetching && "(refreshing)"}</p>;
}

function BookList() {
  const { data } = useQuery("books", getBooks, { staleTime: 5000 });
  if (!data) return <p>Loading list...</p>;
  return (
    <ul>
      {data.slice(0, 4).map((b) => (
        <li key={b.id}>{b.title}</li>
      ))}
    </ul>
  );
}

export default function App() {
  const [showList, setShowList] = useState(true);
  return (
    <>
      <button onClick={() => setShowList((s) => !s)}>{showList ? "Hide" : "Show"} list</button>{" "}
      <button onClick={() => invalidate("books", getBooks)}>Invalidate</button>
      <BookCount />
      {showList && <BookList />}
    </>
  );
}
Nothing logged yet.

One request for two components. Hide and show the list within five seconds: instant, no request. Wait longer than five seconds, show it again: the cached list appears instantly and a background refetch runs, because the data is stale. Invalidate marks the entry stale and refetches it because someone is watching.

That's the whole model. TanStack Query adds the rest: garbage collection, retries with backoff, window-focus and reconnect triggers, request cancellation, structural sharing (keeping unchanged parts of the data referentially equal so memoized children don't re-render), pagination, mutations, Suspense integration, SSR hydration and DevTools.

TanStack Query#

TanStack Query (version 5.108 in the sandbox, formerly React Query) is the most widely used server-state library for React. You create one QueryClient (the cache), provide it at the root, and call useQuery with a key and a query function.

import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";

const queryClient = new QueryClient(); // create once, outside components

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <Books />
    </QueryClientProvider>
  );
}

function Books() {
  const { data, status, fetchStatus, error } = useQuery({
    queryKey: ["books"],
    queryFn: ({ signal }) => fakeFetch("/books", { signal }),
  });
  // ...
}

Mapped to the toy: QueryClient is the cache Map plus its policies. useQuery is our hook: it subscribes a query observer to one cache entry (through useSyncExternalStore) and triggers fetches according to the options. The query function receives an AbortSignal, so a request whose query is cancelled can actually be aborted.

Two kinds of status#

A query result carries two independent statuses, and mixing them up is the most common source of flickering spinners:

  • status answers "do I have data?": "pending" (no data yet), "error", or "success". Booleans: isPending, isError, isSuccess.
  • fetchStatus answers "is the query function running?": "fetching", "paused" (wanted to fetch but the network is offline), or "idle". Booleans: isFetching, isPaused.

A background refetch is status: "success" with fetchStatus: "fetching": you have data, keep showing it, maybe show a subtle refresh indicator. Show a full spinner only when isPending. (isLoading is isPending && isFetching, the first load.)

Query keys#

The key identifies the data. It's an array, hashed deterministically (object keys are sorted, so { page: 1, q: "x" } and { q: "x", page: 1 } are the same key). Everything the query function uses must be in the key. When the key changes, it's a different cache entry, and the query fetches it (or serves it from cache).

useQuery({ queryKey: ["books"], queryFn: fetchBooks });
useQuery({ queryKey: ["books", { q }], queryFn: () => fetchBooks(q) });
useQuery({ queryKey: ["book", id], queryFn: () => fetchBook(id) });

Keys are hierarchical for invalidation: invalidateQueries({ queryKey: ["books"] }) matches ["books"] and ["books", { q: "x" }] by prefix. Teams usually centralize keys and options with queryOptions, so the key and the function can't drift apart:

import { queryOptions } from "@tanstack/react-query";

export const bookQueries = {
  all: () => queryOptions({ queryKey: ["books"], queryFn: () => fetchBooks() }),
  search: (q: string) => queryOptions({ queryKey: ["books", { q }], queryFn: () => fetchBooks(q) }),
  detail: (id: number) => queryOptions({ queryKey: ["book", id], queryFn: () => fetchBook(id) }),
};

useQuery(bookQueries.detail(3));
queryClient.query(bookQueries.detail(4)).catch(() => {}); // prefetch: fill the cache, ignore errors

In 5.108, queryClient.query() is the imperative call for fetching outside a component. It replaces fetchQuery, prefetchQuery and ensureQueryData, which still work but are marked deprecated, so you'll keep seeing them in existing code. Unlike prefetchQuery, query() rejects on error, hence the .catch when you only want to warm the cache.

staleTime versus gcTime#

These two options are the heart of the cache, and the most asked-about pair in interviews. They measure different things:

  • staleTime (default 0): how long data stays fresh after it's fetched. While fresh, nothing triggers a refetch; the cache answers directly. Once stale, the data is still shown, but the next trigger refetches it in the background. It's a freshness policy.
  • gcTime (default 5 minutes, called cacheTime before v5): how long an inactive entry (no components using it) stays in memory before it's garbage collected. It's a memory policy.

They're independent. A query can be fresh and inactive (you navigated away a second ago), or stale and active (on screen, waiting for a trigger). With the defaults, data is stale immediately, so every trigger refetches; that's deliberately conservative. Raising staleTime is the usual first tuning step: 30 seconds for a list that rarely changes, Infinity for data that never changes (and gcTime: Infinity if it should never be dropped either).

The life of a query cache entry
fetchingqueryFn runningfreshcached, within staleTimestalecached, still showninactiveno observersgarbage collectedgone from the cachedatastaleTimetrigger: mount, window focus, reconnect, interval, invalidatelast observer unmountsgcTime passes (default 5 min)status: "pending", fetchStatus: "fetching", no data yet
Step 1 of 6

The first component using ['books'] mounts. There's no cache entry, so the query fetches. status is pending: there's nothing to show yet.

What triggers a refetch#

A stale query refetches when:

TriggerOptionDefault
A new component using the key mountsrefetchOnMounttrue
The window regains focus (the tab becomes visible)refetchOnWindowFocustrue
The network reconnectsrefetchOnReconnecttrue
A timer ticksrefetchIntervaloff
You invalidate itqueryClient.invalidateQueries(always, if active)

Each option also accepts "always" to refetch even fresh data, and refetchInterval runs regardless of staleness. Invalidation marks matching queries stale and refetches the active ones right away; inactive ones refetch when next used.

Try every trigger here. The sandbox can't change real tab focus or network state, so the buttons drive TanStack's own focusManager and onlineManager, which is also how you'd adapt it to React Native or tests. gcTime is set to 5 seconds so you can watch garbage collection.

Cache playground: staleTime, triggers, gcTime
import { useState } from "react";
import { QueryClient, QueryClientProvider, useQuery, focusManager, onlineManager } from "@tanstack/react-query";
import { fakeFetch } from "guide-tools";

const queryClient = new QueryClient();
let fetches = 0;

async function fetchBooks() {
  const n = ++fetches;
  const books = await fakeFetch("/books", { delay: 800 });
  return { count: books.length, n, at: new Date().toLocaleTimeString() };
}

function Books({ name, staleTime, poll }: { name: string; staleTime: number; poll: boolean }) {
  const q = useQuery({
    queryKey: ["books"],
    queryFn: fetchBooks,
    staleTime,
    gcTime: 5000,
    refetchInterval: poll ? 3000 : false,
  });
  return (
    <div style={{ border: "1px solid #d6d3d1", borderRadius: 8, padding: 8, margin: "6px 0" }}>
      <strong>{name}</strong>{" "}
      <code>
        status: {q.status} · fetchStatus: {q.fetchStatus} · isStale: {String(q.isStale)}
      </code>
      <div>{q.data ? `${q.data.count} books, from fetch #${q.data.n} at ${q.data.at}` : "No data yet"}</div>
    </div>
  );
}

function Playground() {
  const [staleTime, setStaleTime] = useState(0);
  const [showA, setShowA] = useState(true);
  const [showB, setShowB] = useState(false);
  const [poll, setPoll] = useState(false);
  const [online, setOnline] = useState(true);

  return (
    <div>
      <label>
        staleTime{" "}
        <select value={staleTime} onChange={(e) => setStaleTime(Number(e.target.value))}>
          <option value={0}>0 (default)</option>
          <option value={10000}>10 seconds</option>
          <option value={Infinity}>Infinity</option>
        </select>
      </label>{" "}
      <label>
        <input type="checkbox" checked={showA} onChange={(e) => setShowA(e.target.checked)} /> A mounted
      </label>{" "}
      <label>
        <input type="checkbox" checked={showB} onChange={(e) => setShowB(e.target.checked)} /> B mounted
      </label>{" "}
      <label>
        <input type="checkbox" checked={poll} onChange={(e) => setPoll(e.target.checked)} /> Poll every 3s
      </label>
      <div style={{ margin: "6px 0" }}>
        <button
          onClick={() => {
            focusManager.setFocused(false);
            focusManager.setFocused(true);
          }}
        >
          Simulate window focus
        </button>{" "}
        <button
          onClick={() => {
            onlineManager.setOnline(!online);
            setOnline(!online);
          }}
        >
          {online ? "Go offline" : "Reconnect"}
        </button>{" "}
        <button onClick={() => queryClient.invalidateQueries({ queryKey: ["books"] })}>Invalidate</button>
      </div>
      {showA && <Books name="A" staleTime={staleTime} poll={poll} />}
      {showB && <Books name="B" staleTime={staleTime} poll={poll} />}
      {!showA && !showB && <p>No observers: the query is inactive. gcTime is 5s.</p>}
    </div>
  );
}

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <Playground />
    </QueryClientProvider>
  );
}

Things to try:

  • With staleTime 0, mount B: a new fetch, but B shows the cached data immediately. Switch to 10 seconds and remount B quickly: no fetch.
  • Simulate focus with staleTime 0 (refetch) and with Infinity (nothing).
  • Go offline and invalidate: fetchStatus becomes paused. Reconnect and it fetches.
  • Unmount both, wait under 5 seconds, remount: instant data. Wait longer: back to pending, because the entry was collected.

Mutations and invalidation: the reading list adds a book#

Reads are queries; writes are mutations. useMutation doesn't cache anything. It runs a function, tracks its status (isPending, isError, isSuccess), and gives you lifecycle callbacks. Mutations don't retry by default (queries retry 3 times with exponential backoff), because repeating a write is rarely safe.

After a write, the server data you cached is out of date. You have two choices:

  • Invalidate: queryClient.invalidateQueries({ queryKey: ["books"] }). Simple, always correct, costs a refetch.
  • Write the cache directly: queryClient.setQueryData(["books"], (old) => [...old, created]) with the server's response. Saves a request, but now you're responsible for computing the same result the server would.

Invalidating is the default. Set data directly when the response contains everything you need and the refetch is expensive.

Optimistic updates with rollback#

An optimistic update shows the result before the server confirms it, and undoes it if the server says no. With TanStack Query that's three callbacks around the mutation:

  1. onMutate: cancel in-flight fetches for the key (so they can't overwrite your optimistic data), snapshot the current cache, write the optimistic version, and return the snapshot.
  2. onError: put the snapshot back. Its third argument is whatever onMutate returned.
  3. onSettled: invalidate, so the cache ends up matching the server either way. Returning the promise keeps the mutation pending until the refetch finishes.

Tick "Server rejects" to watch the rollback.

Adding a book: optimistic update with rollback
import { useState } from "react";
import { QueryClient, QueryClientProvider, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { fakeFetch } from "guide-tools";

type Book = { id: number; title: string; author: string };
const queryClient = new QueryClient();
const server = { reject: false };

function Books() {
  const { data, isPending, isFetching } = useQuery({
    queryKey: ["books"],
    queryFn: () => fakeFetch("/books", { delay: 300 }) as Promise<Book[]>,
  });
  if (isPending) return <p>Loading...</p>;
  return (
    <>
      <p>{isFetching ? "Syncing with server..." : `${data!.length} books`}</p>
      <ul>
        {data!.slice(-4).map((b) => (
          <li key={b.id} style={{ opacity: b.id < 0 ? 0.5 : 1 }}>
            {b.title} {b.id < 0 && "(saving)"}
          </li>
        ))}
      </ul>
    </>
  );
}

function AddBook() {
  const qc = useQueryClient();
  const [title, setTitle] = useState("");
  const add = useMutation({
    mutationFn: (newTitle: string) =>
      fakeFetch("/books", { method: "POST", body: { title: newTitle, author: "You" }, delay: 1200, fail: server.reject }) as Promise<Book>,
    onMutate: async (newTitle) => {
      await qc.cancelQueries({ queryKey: ["books"] });
      const previous = qc.getQueryData<Book[]>(["books"]);
      qc.setQueryData<Book[]>(["books"], (old = []) => [...old, { id: -Date.now(), title: newTitle, author: "You" }]);
      return { previous };
    },
    onError: (_error, _title, onMutateResult) => {
      qc.setQueryData(["books"], onMutateResult?.previous);
    },
    onSettled: () => qc.invalidateQueries({ queryKey: ["books"] }),
  });

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        if (title.trim()) add.mutate(title.trim());
        setTitle("");
      }}
    >
      <input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="New book title" />
      <button>Add</button>{" "}
      <label>
        <input type="checkbox" onChange={(e) => (server.reject = e.target.checked)} /> Server rejects
      </label>
      {add.isError && <p style={{ color: "#a0461f" }}>Couldn't save: {add.error.message}</p>}
    </form>
  );
}

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <AddBook />
      <Books />
    </QueryClientProvider>
  );
}

Prefetching, dependent and parallel queries#

Prefetching fills the cache before a component asks. Hover a title below: queryClient.query() fetches the detail into the cache, so the click renders instantly. It respects staleTime, so hovering twice doesn't fetch twice.

Dependent queries wait for data they need. The "more by this author" query needs the book's author, so it's disabled until the first query has data (enabled: !!book). That's a waterfall by necessity; keep it to cases where you really need the first answer.

Prefetch on hover, then a dependent query
import { useState } from "react";
import { QueryClient, QueryClientProvider, queryOptions, useQuery, useQueryClient } from "@tanstack/react-query";
import { fakeFetch, books } from "guide-tools";

type Book = (typeof books)[number];
const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: 30_000 } } });

const bookQuery = (id: number) =>
  queryOptions({ queryKey: ["book", id], queryFn: () => fakeFetch(`/books/${id}`, { delay: 800 }) as Promise<Book> });

function Detail({ id }: { id: number }) {
  const { data: book, isPending } = useQuery(bookQuery(id));
  const author = book?.author;
  const more = useQuery({
    queryKey: ["books", { q: author }],
    queryFn: () => fakeFetch(`/books?q=${encodeURIComponent(author!)}`, { delay: 600 }) as Promise<Book[]>,
    enabled: !!author, // dependent: waits for the first query
  });
  if (isPending) return <p>Loading book...</p>;
  return (
    <div>
      <h4>{book!.title}</h4>
      <p>
        {book!.author}, {book!.year}
      </p>
      <p>More by this author: {more.isPending ? "..." : more.data!.map((b) => b.title).join(", ")}</p>
    </div>
  );
}

function List() {
  const qc = useQueryClient();
  const [selected, setSelected] = useState<number | null>(null);
  return (
    <div style={{ display: "flex", gap: 16 }}>
      <ul>
        {books.slice(0, 5).map((b) => (
          <li key={b.id}>
            <button onMouseEnter={() => qc.query(bookQuery(b.id)).catch(() => {})} onClick={() => setSelected(b.id)}>
              {b.title}
            </button>
          </li>
        ))}
      </ul>
      {selected != null && <Detail id={selected} />}
    </div>
  );
}

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <List />
    </QueryClientProvider>
  );
}

Parallel queries need nothing special: two useQuery calls in one component run at the same time. For a dynamic number of queries, use useQueries, which takes an array and returns an array of results:

const results = useQueries({
  queries: ids.map((id) => bookQuery(id)),
  combine: (results) => ({
    books: results.map((r) => r.data).filter(Boolean),
    pending: results.some((r) => r.isPending),
  }),
});

Suspense mode#

useSuspenseQuery suspends instead of returning isPending, so data is always defined and loading UI moves to a <Suspense> boundary (errors go to an error boundary). It works with everything from Suspense and use: changing the key inside startTransition keeps the old content on screen instead of falling back.

useSuspenseQuery with a transition
import { Suspense, useState, useTransition } from "react";
import { QueryClient, QueryClientProvider, useSuspenseQuery } from "@tanstack/react-query";
import { fakeFetch } from "guide-tools";

type Book = { id: number; title: string; year: number };
const queryClient = new QueryClient();

function BookCard({ id }: { id: number }) {
  const { data } = useSuspenseQuery({
    queryKey: ["book", id],
    queryFn: () => fakeFetch(`/books/${id}`, { delay: 900 }) as Promise<Book>,
  });
  return (
    <p>
      #{data.id}: {data.title} ({data.year})
    </p>
  );
}

function Browser() {
  const [id, setId] = useState(1);
  const [isPending, startTransition] = useTransition();
  return (
    <>
      <button onClick={() => setId((i) => (i % 10) + 1)}>Next (falls back)</button>{" "}
      <button onClick={() => startTransition(() => setId((i) => (i % 10) + 1))}>Next in a transition</button>
      <div style={{ opacity: isPending ? 0.5 : 1 }}>
        <Suspense fallback={<p>Loading book...</p>}>
          <BookCard id={id} />
        </Suspense>
      </div>
    </>
  );
}

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <Browser />
    </QueryClientProvider>
  );
}

Go back to a book you've seen: no fallback at all, because the cache answers synchronously.

Rendering on the server and handing the cache to the client (prefetch on the server, dehydrate, then HydrationBoundary in the browser) is covered with Next.js in Data and mutations in Next.js.

SWR: stale-while-revalidate#

SWR (version 2.5 in the sandbox), from Vercel, is named after the HTTP Cache-Control: stale-while-revalidate directive from RFC 5861: serve the cached (stale) response immediately, revalidate in the background, and update when the fresh one arrives. That's exactly the "stale but still shown" behavior above, made the whole philosophy.

The API is smaller. The key is usually the URL, and it's passed to the fetcher:

SWR: shared key, dedupe, optimistic mutate
import useSWR from "swr";
import { fakeFetch } from "guide-tools";

type Book = { id: number; title: string };
let requests = 0;
const fetcher = (path: string) => {
  console.log(`request #${++requests} ${path}`);
  return fakeFetch(path, { delay: 700 }) as Promise<Book[]>;
};

function Count() {
  const { data, isLoading, isValidating } = useSWR("/books", fetcher);
  if (isLoading) return <p>Loading count...</p>;
  return (
    <p>
      {data!.length} books {isValidating && "(revalidating)"}
    </p>
  );
}

function List() {
  const { data, mutate } = useSWR("/books", fetcher);
  async function addBook() {
    const title = `New book ${Math.floor(Math.random() * 1000)}`;
    await mutate(fakeFetch("/books", { method: "POST", body: { title }, delay: 1000 }), {
      optimisticData: (current) => [...(current ?? []), { id: -1, title: `${title} (saving)` }],
      rollbackOnError: true,
      populateCache: false, // the POST returns one book, not the list
      revalidate: true, // so refetch the list afterwards
    });
  }
  return (
    <>
      <button onClick={addBook}>Add a book</button> <button onClick={() => mutate()}>Revalidate</button>
      <ul>{data?.slice(-3).map((b) => <li key={b.id}>{b.title}</li>)}</ul>
    </>
  );
}

export default function App() {
  return (
    <>
      <Count />
      <List />
    </>
  );
}

Both components use the key "/books", so they share one cache entry and one request: SWR deduplicates requests for the same key within dedupingInterval (2 seconds by default). isLoading is true only for the first load with no data; isValidating is true for every fetch, including background ones (the same split as status and fetchStatus). SWR revalidates on mount, focus and reconnect by default, and useSWRMutation from swr/mutation gives you a useMutation-style hook for writes.

SWR or TanStack Query? SWR is smaller and simpler, and suits apps that mostly read. TanStack Query has the richer cache model: explicit staleTime and gcTime, structured keys with prefix invalidation, first-class mutations with lifecycle callbacks, useQueries, infinite queries, and DevTools. For an app with many writes, TanStack Query usually wins.

RTK Query, Apollo and Relay#

If the app already uses Redux Toolkit, RTK Query (shipped in @reduxjs/toolkit/query) gives you the same cache inside the Redux store. You describe an API once, and it generates hooks:

booksApi.ts
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";

export const booksApi = createApi({
  reducerPath: "booksApi",
  baseQuery: fetchBaseQuery({ baseUrl: "/api" }),
  tagTypes: ["Book"],
  endpoints: (build) => ({
    getBooks: build.query<Book[], void>({ query: () => "books", providesTags: ["Book"] }),
    addBook: build.mutation<Book, Partial<Book>>({
      query: (body) => ({ url: "books", method: "POST", body }),
      invalidatesTags: ["Book"], // refetches every query that provides "Book"
    }),
  }),
});

export const { useGetBooksQuery, useAddBookMutation } = booksApi;

The big difference is invalidation by tags declared on endpoints instead of by key prefix, and the cache lives in Redux, so it shows up in Redux DevTools. Unused data is kept for keepUnusedDataFor (60 seconds by default), its equivalent of gcTime. Refetching on focus and reconnect needs setupListeners(store.dispatch). Pick it when you're already on Redux Toolkit; don't adopt Redux to get it.

For GraphQL, Apollo Client and Relay go further: they normalize responses into a cache of entities by type and id, so updating Book:3 in one query updates every query that includes it. Relay adds compile-time fragments colocated with components. They're the right tool when the backend is GraphQL; TanStack Query works with GraphQL too, but caches by query key, not by entity.

TanStack QuerySWRRTK QueryApollo / Relay
Cache unitquery keykey (often URL)endpoint + argsnormalized entities
Invalidationkey prefixkey, mutatetagsentity updates, refetch
MutationsuseMutationmutate, useSWRMutationgenerated hooksGraphQL mutations
Best fitany REST or RPC appread-heavy, minimalexisting Redux appsGraphQL backends

Pitfalls#

Check your understanding#

PredictTwo components, one key

With default options, component A mounts and fetches ["books"]. Three seconds later (long after A's data arrived), component B mounts and uses the same key. How many requests have been made, and what does B render first? What changes with staleTime: 60_000?

Quick checkstaleTime or gcTime

Users complain that the dashboard refetches its reports every time they switch tabs, and the reports only change hourly. What do you change?

Fix itThe search that never searches

Typing in the box should filter the books by the server's search. It doesn't. Fix it without adding effects.

import { useState } from "react";
import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";
import { fakeFetch } from "guide-tools";

type Book = { id: number; title: string; author: string };
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });

function Search() {
  const [q, setQ] = useState("");
  const { data } = useQuery({
    queryKey: ["books"],
    queryFn: () => fakeFetch(`/books?q=${encodeURIComponent(q)}`, { delay: 100 }) as Promise<Book[]>,
  });
  return (
    <div>
      <input aria-label="Search" value={q} onChange={(e) => setQ(e.target.value)} />
      <ul>{data?.map((b) => <li key={b.id}>{b.title}</li>)}</ul>
    </div>
  );
}

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <Search />
    </QueryClientProvider>
  );
}
Fix itThe book that doesn't appear

Adding a book succeeds on the server (check the console), but the list doesn't show it. Make the new book appear after a successful add.

import { useState } from "react";
import { QueryClient, QueryClientProvider, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { fakeFetch } from "guide-tools";

type Book = { id: number; title: string };
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });

function Books() {
  const { data } = useQuery({ queryKey: ["books"], queryFn: () => fakeFetch("/books", { delay: 100 }) as Promise<Book[]> });
  return <ul>{data?.map((b) => <li key={b.id}>{b.title}</li>)}</ul>;
}

function AddBook() {
  const qc = useQueryClient();
  const [title, setTitle] = useState("");
  const add = useMutation({
    mutationFn: (t: string) => fakeFetch("/books", { method: "POST", body: { title: t }, delay: 100 }),
    onSuccess: (created) => console.log("server saved", created),
  });
  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        add.mutate(title);
        setTitle("");
      }}
    >
      <input aria-label="Title" value={title} onChange={(e) => setTitle(e.target.value)} />
      <button>Add</button>
    </form>
  );
}

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <AddBook />
      <Books />
    </QueryClientProvider>
  );
}
Nothing logged yet.
Explain it out loudWhy not Redux for server data?

An interviewer asks: "We keep API data in Redux with loading flags. Why would we switch to something like TanStack Query?"

Interview angle

Say it in 30 seconds

Server state is a cache of data the server owns, not state my app owns. It goes stale, other people change it, and many components want it. So I use a cache manager like TanStack Query: data is keyed by everything that identifies it, concurrent requests are deduplicated, staleTime says how long data stays fresh, gcTime says how long unused data stays in memory, stale data refetches on mount, window focus, reconnect or invalidation, and mutations invalidate the keys they affect, optionally with optimistic updates that roll back on error. That leaves the client store for genuinely client state.

What's the difference between server state and client state?

basic

Explain staleTime versus gcTime in TanStack Query.

intermediate

How should you design query keys?

intermediate

Walk me through an optimistic update with rollback.

senior

What happens when a user switches back to a tab running TanStack Query?

intermediate

Two components on the same screen call useQuery with the same key. What happens on mount, and later when the data changes?

intermediate

SWR or TanStack Query?

basic

Recap#

  • Server state is a cache of data you don't own. It needs keys, deduplication, a freshness policy, refetch triggers, invalidation and garbage collection, which is what TanStack Query, SWR and RTK Query provide.
  • Query keys identify data and must include every variable the query function uses. Keys are hierarchical, so invalidation can match by prefix.
  • staleTime (default 0) is how long data stays fresh; gcTime (default 5 minutes) is how long unused data stays in memory. Stale data is still shown; it refetches on mount, focus, reconnect, interval or invalidation.
  • status says whether you have data, fetchStatus says whether a request is running. Spinner on isPending, subtle indicator on isFetching.
  • Mutations invalidate or update the cache. Optimistic updates cancel, snapshot, write, roll back on error and invalidate when settled.
  • SWR is the minimal stale-while-revalidate take; RTK Query puts the cache in Redux with tag invalidation; Apollo and Relay normalize GraphQL entities.

Sources#