Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 30 min · revision 3

Lab: Server State with a Query Cache

Move the reading list from hand-written effects to TanStack Query: query keys and stale times, invalidation after a mutation, an optimistic add that rolls back, and an error boundary with retry.

Contentsand lesson path

What you will learn

  • Fetch server data in components without race conditions, rendering loading, error and empty states and recovering with an error boundary.
  • Manage server state with a query cache such as TanStack Query: query keys, stale times, invalidation after mutations and optimistic updates with rollback.

Prerequisites: React Components & State, Async JavaScript & Fetch

01. Goal and setup

The fetching lesson left you with a search page that models its own statuses and defends its own effects. That works, and it is the right thing to understand — but almost every screen in a real product repeats the pattern, so the ecosystem maintains it for you. A query cache keeps a map from a key to server data: it deduplicates concurrent requests, keeps results fresh for a configurable time, refetches when a key changes, and pairs queries with mutations that can invalidate what they affect. This lab rebuilds the reading list on TanStack Query and watches the server to see exactly what the cache does.

You need: Node 22 or later with npm. The lab is self-contained: the files below create a small Vite page and a local books API, an extended copy of the one from the fetching lesson. It was checked on 26 November 2026 with the versions pinned in package.json: @tanstack/react-query 5.108.4, React 19.3.1, Vite 8.4.0 and @vitejs/plugin-react 6.3.0. Each expected output lists what the page shows, and its server stats lines are what curl -s http://localhost:4001/api/__stats prints at that moment; the outputs were checked by driving the page in Chromium with Playwright 1.64.1. In an empty folder, save package.json and install:

JSON · package.json
{
  "name": "reading-list-lab",
  "private": true,
  "type": "module",
  "dependencies": {
    "@tanstack/react-query": "5.108.4",
    "react": "19.3.1",
    "react-dom": "19.3.1"
  },
  "devDependencies": {
    "@vitejs/plugin-react": "6.3.0",
    "vite": "8.4.0"
  }
}
Terminal
npm install
Files for this lab
reading-list-lab/
├── package.json
├── vite.config.js
├── index.html
├── mock-api.mjs              the books API, extended below
└── src/
    ├── App.jsx               shows one step at a time (?step=1 … 5)
    ├── WidgetBoundary.jsx    the error boundary from the fetching lesson
    ├── main.jsx              QueryClientProvider setup (step 1)
    ├── ReadingList.jsx       a cached query (step 1)
    ├── SearchCache.jsx       keys and staleTime (step 2)
    ├── AddBookButton.jsx     mutation plus invalidation (step 3)
    ├── OptimisticAddButton.jsx  optimistic add with rollback (step 4)
    └── FeaturedBook.jsx      a failing widget behind a boundary (step 5)

Save the complete mock-api.mjs below. It keeps stats, supports CORS, manages reading-list mutations, and includes control endpoints to simulate failures:

JS · mock-api.mjs (complete mock server with CORS and stats)
import { createServer } from 'node:http';

const BOOKS = [
  { id: 1, title: 'React Quickstart', author: 'Ada Fields' },
  { id: 2, title: 'React Patterns', author: 'Grace Oduya' },
  { id: 3, title: 'Refactoring UIs', author: 'Lin Mao' },
  { id: 4, title: 'REST in Practice', author: 'Sam Yates' },
  { id: 5, title: 'JavaScript: The Good Bits', author: 'Ana Duarte' },
];
const DELAYS = { '': 80, re: 200, react: 50 };

const stats = { searches: 0, listFetches: 0, adds: 0, addFailures: 0 };
let readingList = [];
let addFailing = false;
let brokenPayload = false;
let failOk = false;

createServer((req, res) => {
  const url = new URL(req.url, 'http://localhost');
  const send = (status, body) => {
    res.writeHead(status, {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type',
    });
    res.end(JSON.stringify(body));
  };
  if (req.method === 'OPTIONS') {
    res.writeHead(204, {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type',
    });
    return res.end();
  }
  if (req.method === 'POST' && url.pathname === '/api/__control') {
    let raw = '';
    req.on('data', (c) => (raw += c));
    req.on('end', () => {
      const body = JSON.parse(raw);
      if (body.addFailing !== undefined) addFailing = Boolean(body.addFailing);
      if (body.brokenPayload !== undefined) {
        brokenPayload = Boolean(body.brokenPayload);
      }
      if (body.failOk !== undefined) failOk = Boolean(body.failOk);
      send(200, { ok: true });
    });
    return;
  }
  if (url.pathname === '/api/__stats') return send(200, stats);
  if (url.pathname === '/api/books') {
    stats.searches += 1;
    const q = (url.searchParams.get('q') ?? '').trim().toLowerCase();
    if (q === 'fail' && !failOk) {
      return setTimeout(() => send(500, { error: 'Search is down' }), 20);
    }
    const results = brokenPayload
      ? null
      : BOOKS.filter((b) => b.title.toLowerCase().includes(q));
    return setTimeout(() => send(200, { query: q, results }), DELAYS[q] ?? 40);
  }
  if (url.pathname === '/api/reading-list' && req.method === 'GET') {
    stats.listFetches += 1;
    return setTimeout(() => send(200, { results: [...readingList] }), 30);
  }
  if (url.pathname === '/api/reading-list' && req.method === 'POST') {
    let raw = '';
    req.on('data', (c) => (raw += c));
    req.on('end', () => {
      if (addFailing) {
        stats.addFailures += 1;
        return setTimeout(() => send(500, { error: 'Could not save' }), 40);
      }
      const body = JSON.parse(raw || '{}');
      const book = BOOKS.find((b) => b.id === Number(body.id)) ?? {
        id: Number(body.id),
        title: body.title ?? 'Custom Book',
      };
      stats.adds += 1;
      readingList = [...readingList, book];
      setTimeout(() => send(201, { results: [...readingList] }), 60);
    });
    return;
  }
  send(404, { error: 'Not found' });
}).listen(4001);

Start the server with node mock-api.mjs (port 4001 avoids colliding with Vite preview on 4173). The failure switches are set with a POST to /api/__control, for example curl -s -X POST -d '{"addFailing":true}' http://localhost:4001/api/__control. The page is three small files plus one component per step; App.jsx imports all of them, so create every file before the first run (the step components are printed in steps 1 to 5):

JSX · vite.config.js, index.html and src/App.jsx
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({ plugins: [react()] });

// index.html: <div id="root"></div> and
// <script type="module" src="/src/main.jsx"></script> inside <body>

// src/App.jsx
import { useState } from 'react';
import ReadingList from './ReadingList.jsx';
import SearchCache from './SearchCache.jsx';
import AddBookButton from './AddBookButton.jsx';
import OptimisticAddButton from './OptimisticAddButton.jsx';
import { FeaturedPanel } from './FeaturedBook.jsx';

const apiBase = 'http://localhost:4001';
// Open http://localhost:5173/?step=1 (or 2 … 5) to see one step at a time.
const step = new URLSearchParams(window.location.search).get('step') ?? '1';
const patterns = { id: 2, title: 'React Patterns' };

export default function App() {
  const [second, setSecond] = useState(false);
  return (
    <main>
      <h1>Reading list lab, step {step}</h1>
      {['1', '3', '4'].includes(step) && <ReadingList apiBase={apiBase} />}
      {step === '2' && (
        <>
          <SearchCache apiBase={apiBase} />
          <button type="button" onClick={() => setSecond(true)}>
            Mount a second search
          </button>
          {second && <SearchCache apiBase={apiBase} />}
        </>
      )}
      {step === '3' && <AddBookButton apiBase={apiBase} bookId={1} />}
      {step === '4' && <OptimisticAddButton apiBase={apiBase} book={patterns} />}
      {step === '5' && <FeaturedPanel apiBase={apiBase} />}
    </main>
  );
}
JSX · src/WidgetBoundary.jsx (as in the fetching lesson)
import { Component } from 'react';

export default class WidgetBoundary extends Component {
  state = { failed: false };

  static getDerivedStateFromError() {
    return { failed: true };
  }

  render() {
    if (this.state.failed) {
      return (
        <p role="alert">
          This panel failed to render.{' '}
          <button type="button" onClick={this.props.onRetry}>
            Retry
          </button>
        </p>
      );
    }
    return this.props.children;
  }
}

Run the page with npx vite in a second terminal. At the start of every step, restart the API (Ctrl+C, then node mock-api.mjs) so that its counters start at zero, then open or reload http://localhost:5173/?step=N for that step.

02. Step 1: your first cached query

A cache needs an owner. Create one QueryClient for the whole app — outside any component — and hand it to a provider. This lab disables automatic retries so failures show up immediately:

JSX · src/main.jsx
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import App from './App.jsx';

const queryClient = new QueryClient({
  defaultOptions: { queries: { retry: false } },
});

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </StrictMode>,
);
JSX · src/ReadingList.jsx
import { useQuery } from '@tanstack/react-query';

export default function ReadingList({ apiBase }) {
  const query = useQuery({
    queryKey: ['reading-list'],
    queryFn: () =>
      fetch(`${apiBase}/api/reading-list`).then((res) => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json();
      }),
  });
  if (query.isPending) {
    return <p role="status">Loading your list…</p>;
  }
  if (query.isError) {
    return <p role="alert">Could not load your list: {query.error.message}</p>;
  }
  if (query.data.results.length === 0) {
    return <p>Your reading list is empty.</p>;
  }
  return (
    <ul>
      {query.data.results.map((b) => (
        <li key={b.id}>{b.title}</li>
      ))}
    </ul>
  );
}
Expected output (open ?step=1, wait for the list, then curl the stats)
first render            -> "Loading your list…"
after the fetch lands   -> "Your reading list is empty."
server stats: {"searches":0,"listFetches":1,"adds":0,"addFailures":0}

Compare this with the hand-written version: no useState, no useEffect, no ignore flag — the statuses come back as fields on the query object (isPending, isError, data), and the effect bookkeeping from the fetching lesson now happens inside the cache. The server counted exactly one list fetch, even though Strict Mode mounted the list twice in development: the cache deduplicated the two identical requests.

03. Step 2: query keys and stale times

The key is the cache address. Every value the query function depends on belongs in it — here the search text — and staleTime sets how long a result is trusted before a new mount bothers the server again:

JSX · src/SearchCache.jsx
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';

export default function SearchCache({ apiBase }) {
  const [query, setQuery] = useState('');
  const search = useQuery({
    queryKey: ['books', query],
    queryFn: () =>
      fetch(`${apiBase}/api/books?q=${encodeURIComponent(query)}`).then((res) => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json();
      }),
    enabled: query.trim().length > 0,
    staleTime: 30_000,
  });
  return (
    <>
      <label>
        Search books
        <input value={query} onChange={(e) => setQuery(e.target.value)} />
      </label>
      {search.isPending && query.trim().length > 0 && (
        <p role="status">Searching…</p>
      )}
      {search.isError && (
        <p role="alert">Search failed: {search.error.message}</p>
      )}
      {search.data && (
        <ul>
          {search.data.results.map((b) => (
            <li key={b.id}>{b.title}</li>
          ))}
        </ul>
      )}
      {query.trim().length === 0 && <p>Type to search.</p>}
    </>
  );
}
Expected output (open ?step=2; paste each word, curl the stats after each action)
paste "react" in search 1    -> list: React Quickstart, React Patterns
server stats: {"searches":1,"listFetches":0,"adds":0,"addFailures":0}
paste "react" in search 2    -> list: React Quickstart, React Patterns
server stats: {"searches":1,"listFetches":0,"adds":0,"addFailures":0}
replace it with "java"       -> list: JavaScript: The Good Bits
server stats: {"searches":2,"listFetches":0,"adds":0,"addFailures":0}
back to "react"              -> list: React Quickstart, React Patterns
server stats: {"searches":2,"listFetches":0,"adds":0,"addFailures":0}

Four actions, two requests. The second search box was mounted later and has its own state, yet its first query was answered straight from memory, because both components read the same QueryClient and the entry was inside its 30-second stale window. A different key meant a different cache entry and a real request; returning to the first key found its entry still fresh. The cache lives in the client, not in the component tree, so unmounting a component does not throw its data away — the entry stays until gcTime (five minutes by default) runs out after nothing uses it.

Paste each word rather than typing it. The key changes on every keystroke, so typing "react" letter by letter sends five requests (r, re, rea, reac, react) and the counters will not match; that is also why real search boxes debounce the text before it reaches queryKey.

04. Step 3: a mutation that invalidates

Writes use useMutation. A mutation does not know which queries its change affects — you tell it, in onSuccess, by invalidating the keys whose data is now stale:

JSX · src/AddBookButton.jsx
import { useMutation, useQueryClient } from '@tanstack/react-query';

export default function AddBookButton({ apiBase, bookId }) {
  const client = useQueryClient();
  const mutation = useMutation({
    mutationFn: (id) =>
      fetch(`${apiBase}/api/reading-list`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id }),
      }).then((res) => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json();
      }),
    onSuccess: () => client.invalidateQueries({ queryKey: ['reading-list'] }),
  });
  return (
    <button type="button" onClick={() => mutation.mutate(bookId)}>
      Add book {bookId}
    </button>
  );
}
Expected output (open ?step=3, click once, then curl the stats)
click "Add book 1"      -> list: React Quickstart (after refetch)
server stats: {"searches":0,"listFetches":2,"adds":1,"addFailures":0}

The stats tell the story: one adds on the server, and the second listFetches is the invalidation doing its work — the key was marked stale, and because the list was on screen, the cache refetched it and the new title appeared. You never moved the server's answer into state by hand.

05. Step 4: optimistic updates with rollback

Invalidation shows the change after a round trip. An optimistic update shows it immediately by writing the expected result into the cache first — and needs a rollback for when the server disagrees. The three hooks run in order: onMutate before the request, onError if it fails, onSettled either way:

JSX · src/OptimisticAddButton.jsx
import { useMutation, useQueryClient } from '@tanstack/react-query';

async function addToReadingList(apiBase, id) {
  const res = await fetch(`${apiBase}/api/reading-list`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ id }),
  });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

export default function OptimisticAddButton({ apiBase, book }) {
  const client = useQueryClient();
  const mutation = useMutation({
    mutationFn: (id) => addToReadingList(apiBase, id),
    onMutate: async () => {
      await client.cancelQueries({ queryKey: ['reading-list'] });
      const previous = client.getQueryData(['reading-list']);
      client.setQueryData(['reading-list'], (old) => ({
        results: [...(old?.results ?? []), book],
      }));
      return { previous };
    },
    onError: (_error, _id, context) => {
      client.setQueryData(['reading-list'], context.previous);
    },
    onSettled: () => client.invalidateQueries({ queryKey: ['reading-list'] }),
  });
  return (
    <button type="button" onClick={() => mutation.mutate(book.id)}>
      Add {book.title}
    </button>
  );
}
Expected output (switch on addFailing with curl first, then open ?step=4 and click)
click "Add React Patterns" -> list: React Patterns
the request fails          -> "Your reading list is empty."
server stats: {"searches":0,"listFetches":2,"adds":0,"addFailures":1}

Follow the recording. Clicking Add put "React Patterns" on screen at once — onMutate wrote it into the cache before any request could answer. The server then answered 500, onError restored the snapshot taken a moment earlier, and the list was empty again. The onSettled invalidation refetched as well, so even the rollback converges with what the server actually has. cancelQueries stops an in-flight refetch from landing mid-update and overwriting the optimistic value with old data.

06. Step 5: a failing widget behind a boundary

Queries can also throw on purpose. Let the widget rethrow its query error during render, and the boundary from the fetching lesson contains it; the retry remounts the widget, and the cache refetches an errored query on mount:

JSX · src/FeaturedBook.jsx (the widget and its panel)
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import WidgetBoundary from './WidgetBoundary.jsx';

export default function FeaturedBook({ apiBase }) {
  const query = useQuery({
    queryKey: ['featured'],
    queryFn: async () => {
      const res = await fetch(`${apiBase}/api/books?q=react`);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const data = await res.json();
      if (data.results === null) throw new Error('malformed payload');
      return data;
    },
    retry: false,
  });
  if (query.isPending) {
    return <p role="status">Picking a featured book…</p>;
  }
  if (query.isError) {
    throw query.error;
  }
  return <p>Featured today: {query.data.results[0].title}</p>;
}

export function FeaturedPanel({ apiBase }) {
  const [attempt, setAttempt] = useState(0);
  return (
    <WidgetBoundary key={attempt} onRetry={() => setAttempt((a) => a + 1)}>
      <FeaturedBook apiBase={apiBase} />
    </WidgetBoundary>
  );
}
Expected output (brokenPayload on before opening ?step=5, off before clicking Retry)
malformed payload       -> alert "This panel failed to render. Retry"
click "Retry" (fixed)   -> "Featured today: React Quickstart"

The boundary caught the rethrown error, the fallback appeared, and — after the server was healed — one click on Retry remounted the widget and the cache refetched. Split the two failure styles in your head: errors you expect (a 500, an empty list) belong in statuses; errors you did not expect belong to a boundary. Query options such as throwOnError make this division explicit in larger apps.

07. Troubleshooting

08. Check your understanding

Practice check · 3 questions

Cache behaviour

Predict what the cache does.

Q1. A list query uses `staleTime: 60_000` under default settings. You navigate back to it two minutes later. What happens?
Q2. Two components both useQuery with queryKey ["books", q] but different values of q. What does the cache hold?
Q3. In the optimistic add, where does the rollback get the previous list from?
Practice only: not graded, not saved, not evidence.

09. Apply it: stretch tasks

Take the book-search practice project the rest of the way:

  1. Give each query a considered stale time: near zero for search, a minute for the reading list, and record why each value suits its data.
  2. Combine the pieces: a debounced search writing into ["books", q], the list query, and an optimistic add with rollback, on one screen.
  3. Break each safety net on purpose — drop the ignore logic, remove the cancelQueries call, skip the rollback — and note what the user sees each time. You now have your own reasons for every line.

10. Review prompt

Without looking back: what does a query key identify, and what must go into it? What did invalidation cost and gain in the step 3 recording? Name the three mutation hooks of an optimistic update in order and the job of each. Where does the cache live — component, provider, or client? And which errors belong to statuses, which to a boundary?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check