Skip to main content

Web frameworks · Intermediate · 28 min

Fetch and cache server data in React with TanStack Query

By Padding · Updated 18 Nov 2026
Debian (node:26 image) · Node.js 26.13 · React 19.3.1 · TanStack Query 5.108.0 · Vite 8.3

You will replace a hand-written fetch effect with TanStack Query 5.108 in a React 19.3 app, and end with a paginated book list that loads from cache, refreshes in the background and shows new books before the server confirms them.

On this page

Fetching in an effect works for one screen. Then the questions pile up. Should the list load again when the reader comes back to it? What if two components need the same data? How do you show a new item straight away and undo it if the server refuses? Every app ends up writing its own cache to answer them, usually with bugs.

TanStack Query is that cache, written once. You give it a key and a function that returns a promise. It stores the result under the key, shares it between components, decides when the data is old, refreshes it in the background and retries failures. Your components only read the result.

In this tutorial you build a small library catalogue with Vite, React 19.3 and TypeScript, against a local JSON API you write yourself in a few lines of Node.js. You start with a fetch effect so you can see what it costs, swap it for useQuery, tune how long data counts as fresh, add pages, add books with useMutation, make new books appear before the server answers, and look inside the cache with the devtools. The useEffect tutorial explains why a fetch in an effect needs care; this one shows what to use instead.

Commands are for a Linux or macOS shell, or WSL on Windows. You need three terminals: one for the API, one for the Vite dev server and one for everything else.

Step 1 · Create the project and a local API

Scaffold a React and TypeScript project, pin React, and install TanStack Query at an exact version so what you see matches this page:

Bash
cd ~
npm create vite@9.3.4 library-query -- --template react-ts --no-interactive
cd library-query
npm install
npm install --save-exact react@19.3.1 react-dom@19.3.1 @tanstack/react-query@5.108.0

Now the API. Create api/server.mjs, a Node.js server with no dependencies. It serves twelve books five at a time, accepts new ones, refuses duplicates with 409 Conflict, and waits 600 milliseconds before every answer so you can see loading states. It also prints each request, which is how you will count them:

Bash
mkdir -p api
cat > api/server.mjs <<'JS'
import { createServer } from 'node:http'

const PAGE_SIZE = 5
const books = [
  { id: 1, title: 'Things Fall Apart', author: 'Chinua Achebe' },
  { id: 2, title: 'Nervous Conditions', author: 'Tsitsi Dangarembga' },
  { id: 3, title: 'Homegoing', author: 'Yaa Gyasi' },
  { id: 4, title: 'So Long a Letter', author: 'Mariama Bâ' },
  { id: 5, title: 'Petals of Blood', author: 'Ngũgĩ wa Thiong’o' },
  { id: 6, title: 'Half of a Yellow Sun', author: 'Chimamanda Ngozi Adichie' },
  { id: 7, title: 'Season of Migration to the North', author: 'Tayeb Salih' },
  { id: 8, title: 'The Famished Road', author: 'Ben Okri' },
  { id: 9, title: 'Stay with Me', author: 'Ayọ̀bámi Adébáyọ̀' },
  { id: 10, title: 'The Old Drift', author: 'Namwali Serpell' },
  { id: 11, title: 'The Beautyful Ones Are Not Yet Born', author: 'Ayi Kwei Armah' },
  { id: 12, title: 'Death and the King’s Horseman', author: 'Wole Soyinka' },
]
let nextId = 13

function send(res, status, body) {
  res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' })
  res.end(JSON.stringify(body))
}

createServer(async (req, res) => {
  const url = new URL(req.url, 'http://localhost')
  console.log(req.method, url.pathname + url.search)
  await new Promise((resolve) => setTimeout(resolve, 600))

  if (req.method === 'GET' && url.pathname === '/api/books') {
    const totalPages = Math.ceil(books.length / PAGE_SIZE)
    const page = Math.min(Math.max(1, Number(url.searchParams.get('page')) || 1), totalPages)
    const start = (page - 1) * PAGE_SIZE
    return send(res, 200, { page, totalPages, books: books.slice(start, start + PAGE_SIZE) })
  }

  if (req.method === 'POST' && url.pathname === '/api/books') {
    let raw = ''
    for await (const chunk of req) raw += chunk
    let input = {}
    try { input = JSON.parse(raw) } catch {}
    const title = String(input.title ?? '').trim()
    const author = String(input.author ?? '').trim()
    if (!title || !author) return send(res, 400, { error: 'Title and author are required' })
    if (books.some((b) => b.title.toLowerCase() === title.toLowerCase())) {
      return send(res, 409, { error: `${title} is already in the catalogue` })
    }
    const book = { id: nextId++, title, author }
    books.unshift(book)
    return send(res, 201, book)
  }

  send(res, 404, { error: 'Not found' })
}).listen(3001, '127.0.0.1', () => console.log('API on http://localhost:3001'))
JS

Data lives in memory, so restarting the server resets the catalogue. New books go to the front of the list, so they land on page 1.

Point Vite at it. Writing the whole vite.config.ts again adds a proxy, so the browser calls /api/... on the same origin as the page and Vite forwards the request to port 3001, in both the dev server and the preview server:

Bash
cat > vite.config.ts <<'TS'
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'

// https://vite.dev/config/
const proxy = { '/api': 'http://127.0.0.1:3001' }

export default defineConfig({
  plugins: [react()],
  server: { proxy },
  preview: { proxy },
})
TS

Replace the starter page with a shell and a small stylesheet:

Bash
rm -rf src/assets src/App.css
cat > src/index.css <<'CSS'
body { font-family: system-ui, sans-serif; margin: 2rem auto; max-width: 36rem; padding: 0 1rem; line-height: 1.5; }
ul { padding-left: 1.2rem; }
form, nav { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: end; margin: 1rem 0; }
label { display: grid; font-size: 0.9rem; }
.status { color: #555; font-size: 0.9rem; }
.placeholder, .saving { opacity: 0.5; }
[role="alert"] { color: #a40000; }
CSS
cat > src/App.tsx <<'TSX'
export default function App() {
  return (
    <main>
      <h1>Library</h1>
    </main>
  )
}
TSX

Start the API in your first terminal and leave it running:

Bash
node api/server.mjs

Start the dev server in your second terminal and leave it running too:

Bash
npm run dev

Check it worked

The first terminal prints API on http://localhost:3001. The second shows VITE v8. and Local: http://localhost:5173/. In the third terminal, ask the API for page 1 through the Vite proxy:

Bash
curl -s 'http://localhost:5173/api/books?page=1'

After a short pause you get JSON starting with {"page":1,"totalPages":3,"books":[{"id":1,"title":"Things Fall Apart", and the API terminal prints GET /api/books?page=1. Open http://localhost:5173/ in the browser: the page shows the heading "Library".

Step 2 · Fetch the list in an effect and see what it costs

Start the way many apps do. Put the API calls and types in one file, src/api.ts. fetchBooks takes an optional AbortSignal, which lets a caller cancel a request it no longer needs:

Bash
cat > src/api.ts <<'TS'
export type Book = { id: number; title: string; author: string }
export type BookPage = { page: number; totalPages: number; books: Book[] }
export type NewBook = { title: string; author: string }

export async function fetchBooks(page: number, signal?: AbortSignal): Promise<BookPage> {
  const res = await fetch(`/api/books?page=${page}`, { signal })
  if (!res.ok) throw new Error(`HTTP ${res.status}`)
  return res.json()
}

export async function addBook(input: NewBook): Promise<Book> {
  const res = await fetch('/api/books', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(input),
  })
  const body = await res.json()
  if (!res.ok) throw new Error(body.error ?? `HTTP ${res.status}`)
  return body
}
TS

Now a list component that fetches in an effect, with the ignore flag that stops a late answer from overwriting a newer one, and a button in App that hides and shows it, standing in for a reader leaving a screen and coming back:

Bash
cat > src/BookItem.tsx <<'TSX'
import type { Book } from './api'

export default function BookItem({ book }: { book: Book }) {
  return (
    <li>
      {book.title} by {book.author}
    </li>
  )
}
TSX
cat > src/BookList.tsx <<'TSX'
import { useEffect, useState } from 'react'
import { fetchBooks, type BookPage } from './api'
import BookItem from './BookItem'

export default function BookList() {
  const [data, setData] = useState<BookPage | null>(null)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    let ignore = false
    fetchBooks(1)
      .then((result) => { if (!ignore) setData(result) })
      .catch((err: Error) => { if (!ignore) setError(err.message) })
    return () => { ignore = true }
  }, [])

  if (error) return <p role="alert">Could not load books: {error}</p>
  if (!data) return <p>Loading books…</p>
  return (
    <ul>
      {data.books.map((book) => <BookItem key={book.id} book={book} />)}
    </ul>
  )
}
TSX
cat > src/App.tsx <<'TSX'
import { useState } from 'react'
import BookList from './BookList'

export default function App() {
  const [showBooks, setShowBooks] = useState(true)
  return (
    <main>
      <h1>Library</h1>
      <button type="button" onClick={() => setShowBooks(!showBooks)}>
        {showBooks ? 'Hide books' : 'Show books'}
      </button>
      {showBooks && <BookList />}
    </main>
  )
}
TSX

Check it worked

The page shows "Loading books…" for a moment, then five books starting with "Things Fall Apart by Chinua Achebe". Click Hide books, then Show books: "Loading books…" appears again and the API terminal prints another GET /api/books?page=1. The effect forgot everything when the component left the screen. On first load in development you may also see the request twice, because React's StrictMode runs effects twice to expose missing cleanups. Each repeat is a wait for the reader and, on prepaid mobile data, a cost.

Step 3 · Replace the effect with useQuery

TanStack Query keeps its cache in a QueryClient. Create one and provide it to the whole app in src/main.tsx:

Bash
cat > src/main.tsx <<'TSX'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'

const queryClient = new QueryClient()

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </StrictMode>,
)
TSX

Create the client once, outside any component. If it lived inside App, a re-render could build a new, empty cache.

Every query needs a key: an array that names the data and everything it depends on. Add a helper to src/api.ts so every component builds keys the same way:

Bash
cat >> src/api.ts <<'TS'

export const booksKey = (page: number) => ['books', { page }] as const
TS

['books', { page: 1 }] reads as "books, page 1". The general part comes first, so later you can refer to every page at once with the shorter key ['books']. Anything the query function uses, such as the page number, a search term or a user ID, belongs in the key. When the key changes, TanStack Query treats it as different data.

Replace src/BookList.tsx:

Bash
cat > src/BookList.tsx <<'TSX'
import { useQuery } from '@tanstack/react-query'
import { booksKey, fetchBooks } from './api'
import BookItem from './BookItem'

export default function BookList() {
  const { data, error, isPending } = useQuery({
    queryKey: booksKey(1),
    queryFn: ({ signal }) => fetchBooks(1, signal),
  })

  if (isPending) return <p>Loading books…</p>
  if (!data) return <p role="alert">Could not load books: {error?.message}</p>
  return (
    <ul>
      {data.books.map((book) => <BookItem key={book.id} book={book} />)}
    </ul>
  )
}
TSX

There is no state, no effect and no ignore flag. queryFn receives a signal that TanStack Query aborts when nothing needs the answer any more, and fetchBooks passes it to fetch. isPending is true only while there is no data at all. If the request fails, the query retries three times with growing pauses before it reports the error, so a brief network drop never reaches the reader.

Check it worked

The list loads as before. Click Hide books, then Show books: the books appear at once with no "Loading books…", because they come from the cache. The API terminal still prints a new GET /api/books?page=1. By default, data counts as stale the moment it arrives, so TanStack Query shows the cached copy and quietly asks for a fresh one. Cached data with no component using it is kept for five minutes before it is dropped.

Step 4 · Decide how long data stays fresh

staleTime says how long a result counts as fresh. While it is fresh, showing the list again costs no request. A catalogue that changes a few times a day can be fresh for 30 seconds or more; a price or a seat count needs less. Replace src/BookList.tsx again, adding staleTime, a status line driven by isFetching, and a Refresh button:

Bash
cat > src/BookList.tsx <<'TSX'
import { useQuery } from '@tanstack/react-query'
import { booksKey, fetchBooks } from './api'
import BookItem from './BookItem'

export default function BookList() {
  const { data, error, isPending, isFetching, refetch } = useQuery({
    queryKey: booksKey(1),
    queryFn: ({ signal }) => fetchBooks(1, signal),
    staleTime: 30_000,
  })

  if (isPending) return <p>Loading books…</p>
  if (!data) return <p role="alert">Could not load books: {error?.message}</p>
  return (
    <section aria-busy={isFetching}>
      <p className="status">{isFetching ? 'Updating…' : 'Up to date'}</p>
      {error && <p role="alert">Could not refresh: {error.message}</p>}
      <ul>
        {data.books.map((book) => <BookItem key={book.id} book={book} />)}
      </ul>
      <button type="button" onClick={() => refetch()}>Refresh</button>
    </section>
  )
}
TSX

Two flags now do different jobs. isPending means there is nothing to show yet, so the whole list is replaced by a loading message. isFetching means a request is in flight for any reason, including a background refresh, so only a small status line changes and the books stay on screen. If a background refresh fails, the reader keeps the last good list and sees why it is not newer.

Check it worked

Hide and show the books within 30 seconds: they appear at once and the API terminal prints nothing new. Click Refresh: the status line reads "Updating…" while the books stay put, then "Up to date". Wait more than 30 seconds, switch to another browser tab and back: the status flickers to "Updating…" by itself, because TanStack Query refetches stale queries when the window regains focus. It does the same when the network comes back after being offline, and it pauses queries while the browser reports no connection rather than failing them.

Step 5 · Page through the list without flashing

Add pages. The page number goes in state and in the key, so each page is cached separately. Without more work, moving to page 2 would show "Loading books…" because ['books', { page: 2 }] has no data yet. placeholderData: keepPreviousData keeps showing the last page until the next one arrives, and isPlaceholderData tells you that is what is on screen:

Bash
cat > src/BookList.tsx <<'TSX'
import { keepPreviousData, useQuery } from '@tanstack/react-query'
import { useState } from 'react'
import { booksKey, fetchBooks } from './api'
import BookItem from './BookItem'

export default function BookList() {
  const [page, setPage] = useState(1)
  const { data, error, isPending, isFetching, isPlaceholderData, refetch } = useQuery({
    queryKey: booksKey(page),
    queryFn: ({ signal }) => fetchBooks(page, signal),
    staleTime: 30_000,
    placeholderData: keepPreviousData,
  })

  if (isPending) return <p>Loading books…</p>
  if (!data) return <p role="alert">Could not load books: {error?.message}</p>
  return (
    <section aria-busy={isFetching}>
      <p className="status">{isFetching ? 'Updating…' : 'Up to date'}</p>
      {error && <p role="alert">Could not refresh: {error.message}</p>}
      <ul className={isPlaceholderData ? 'placeholder' : undefined}>
        {data.books.map((book) => <BookItem key={book.id} book={book} />)}
      </ul>
      <nav aria-label="Pages">
        <button type="button" onClick={() => setPage(page - 1)} disabled={page === 1}>
          Previous
        </button>
        <span>Page {page} of {data.totalPages}</span>
        <button
          type="button"
          onClick={() => setPage(page + 1)}
          disabled={isPlaceholderData || page >= data.totalPages}
        >
          Next
        </button>
        <button type="button" onClick={() => refetch()}>Refresh</button>
      </nav>
    </section>
  )
}
TSX

Next is disabled while the placeholder shows, because data.totalPages still belongs to the old page and a second click would skip ahead on stale numbers. The faded list tells the reader the content is about to change.

Check it worked

The list shows "Page 1 of 3". Click Next: page 1 fades for a moment instead of disappearing, then "Half of a Yellow Sun" heads page 2. Click Previous: page 1 appears at once, and the API terminal shows no new request for it because it is still fresh. To make the effect easier to see, set the Network panel in the developer tools to a slow connection.

Step 6 · Add books with useMutation

Reading uses useQuery. Changing data on the server uses useMutation, which runs a function when you ask and tracks whether it is pending or failed. After a successful change the cached list is out of date, so you invalidate it: mark it stale and refetch whatever is on screen. Create src/AddBookForm.tsx:

Bash
cat > src/AddBookForm.tsx <<'TSX'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import type { FormEvent } from 'react'
import { addBook } from './api'

export default function AddBookForm() {
  const queryClient = useQueryClient()
  const mutation = useMutation({
    mutationFn: addBook,
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['books'] }),
  })

  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const form = event.currentTarget
    const fields = new FormData(form)
    mutation.mutate(
      { title: String(fields.get('title')), author: String(fields.get('author')) },
      { onSuccess: () => form.reset() },
    )
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Title
        <input name="title" required />
      </label>
      <label>
        Author
        <input name="author" required />
      </label>
      <button type="submit" disabled={mutation.isPending}>
        {mutation.isPending ? 'Adding…' : 'Add book'}
      </button>
      {mutation.isError && <p role="alert">{mutation.error.message}</p>}
    </form>
  )
}
TSX
cat > src/App.tsx <<'TSX'
import { useState } from 'react'
import AddBookForm from './AddBookForm'
import BookList from './BookList'

export default function App() {
  const [showBooks, setShowBooks] = useState(true)
  return (
    <main>
      <h1>Library</h1>
      <AddBookForm />
      <button type="button" onClick={() => setShowBooks(!showBooks)}>
        {showBooks ? 'Hide books' : 'Show books'}
      </button>
      {showBooks && <BookList />}
    </main>
  )
}
TSX

invalidateQueries({ queryKey: ['books'] }) matches every key that starts with 'books', so all cached pages are marked stale, and the one on screen refetches now. This is why the general part of the key comes first. Because onSuccess returns the promise from invalidateQueries, the mutation stays pending until the fresh list has arrived, so the button reads "Adding…" until the new book is visible. Disabling the button while pending also stops a double submit on a slow connection.

Check it worked

Fill in "Americanah" by "Chimamanda Ngozi Adichie" and click Add book. The button reads "Adding…" for about a second and a half: one wait for the POST, one for the refetch. Then "Americanah" heads page 1 and the form is empty. The API terminal shows POST /api/books followed by GET /api/books?page=1.

Step 7 · Show new books at once and roll back on failure

That second and a half is honest but slow. An optimistic update writes the expected result into the cache before the server answers, and puts the old value back if the request fails. Replace src/AddBookForm.tsx:

Bash
cat > src/AddBookForm.tsx <<'TSX'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import type { FormEvent } from 'react'
import { addBook, booksKey, type BookPage } from './api'

export default function AddBookForm() {
  const queryClient = useQueryClient()
  const mutation = useMutation({
    mutationFn: addBook,
    onMutate: async (input) => {
      // Stop any refetch in flight so it cannot overwrite the optimistic list.
      await queryClient.cancelQueries({ queryKey: ['books'] })
      const previous = queryClient.getQueryData<BookPage>(booksKey(1))
      if (previous) {
        queryClient.setQueryData<BookPage>(booksKey(1), {
          ...previous,
          books: [{ id: -Date.now(), ...input }, ...previous.books].slice(0, 5),
        })
      }
      return { previous }
    },
    onError: (_error, _input, onMutateResult) => {
      if (onMutateResult?.previous) {
        queryClient.setQueryData(booksKey(1), onMutateResult.previous)
      }
    },
    onSettled: () => queryClient.invalidateQueries({ queryKey: ['books'] }),
  })

  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const form = event.currentTarget
    const fields = new FormData(form)
    mutation.mutate(
      { title: String(fields.get('title')), author: String(fields.get('author')) },
      { onSuccess: () => form.reset() },
    )
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Title
        <input name="title" required />
      </label>
      <label>
        Author
        <input name="author" required />
      </label>
      <button type="submit" disabled={mutation.isPending}>
        {mutation.isPending ? 'Adding…' : 'Add book'}
      </button>
      {mutation.isError && <p role="alert">{mutation.error.message}</p>}
    </form>
  )
}
TSX
cat > src/BookItem.tsx <<'TSX'
import type { Book } from './api'

export default function BookItem({ book }: { book: Book }) {
  const saving = book.id < 0
  return (
    <li className={saving ? 'saving' : undefined}>
      {book.title} by {book.author}
      {saving && <span> (saving…)</span>}
    </li>
  )
}
TSX

The order matters:

  1. onMutate runs before the request. It cancels any refetch in flight, saves the current page 1, and writes a copy with the new book on top. The book gets a negative ID so it cannot clash with a real one, and BookItem uses that to show it faded with "(saving…)".
  2. Whatever onMutate returns reaches onError as its third argument. On failure, it writes the saved page back.
  3. onSettled runs after success or failure and invalidates the list, so the cache ends up matching the server either way, with the real ID in place of the temporary one.

Keep optimistic updates for actions that almost always succeed and are easy to undo. For a payment or anything the reader cannot take back, wait for the server.

Check it worked

Add "Born on a Tuesday" by "Elnathan John". It appears at the top of page 1 the moment you click, faded and marked "(saving…)", then turns solid when the server confirms. Now add "Homegoing" by "Yaa Gyasi", which is already in the catalogue. It appears faded, then disappears again, and the form shows "Homegoing is already in the catalogue". The list is back to how it was, and the form keeps what you typed so you can correct it.

Step 8 · Look inside the cache with the devtools

The devtools show every query in the cache, its key, whether it is fresh, stale, fetching or inactive, and the data it holds. Install them and add them inside the provider:

Bash
npm install --save-exact @tanstack/react-query-devtools@5.108.0
cat > src/main.tsx <<'TSX'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'

const queryClient = new QueryClient()

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  </StrictMode>,
)
TSX

Check it worked

A small TanStack logo button appears in the bottom corner of the page. Click it to open the panel. You see a row for ["books",{"page":1}], and one for page 2 if you visited it. Click a row to read its data and its state. Page through the list and watch a key go from fresh to stale after 30 seconds, and hide the books to watch the queries become inactive.

Step 9 · Build for production

The devtools are only included when the code runs in development, so they add nothing to a production bundle. Stop the dev server with Ctrl+C in its terminal, leave the API running, then build:

Bash
npm run build

Preview the build in the second terminal. The preview server uses the same proxy to the API:

Bash
npm run preview

Open http://localhost:4173/. When you are done, stop the preview and the API with Ctrl+C in their terminals, and delete the project:

Bash
cd ~
rm -rf ~/library-query

Check it worked

npm run build ends with built in and a time. The preview shows the same catalogue, including the books you added, since the API kept them in memory, and there is no devtools button.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.