Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

React
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
  • How a Web Page Works: HTML Tags, Elements and Attributes
  • Semantic HTML: header, nav, main, aside and footer as Page Landmarks
  • HTML Forms: Labels, Names, Input Types and Where the Data Goes (GET vs POST)
  • CSS Basics: Selectors, Which Rule Wins, and the Box Model
  • CSS Flexbox vs Grid: A Nav Bar, a Card Row and a Dashboard
  • Responsive CSS: Viewport, Mobile-First Media Queries, clamp() and Dark Mode with Tokens
  • JavaScript for People Who Already Code: Syntax, Modules and Five Surprises
  • JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries
  • Async JavaScript: Promises, async/await, fetch and Promise.all
  • JavaScript in the Page: the DOM, querySelector and Events
  • npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page
  • TypeScript Essentials: Types Checked, Then Erased (Interfaces, Unions, Generics)
  • Why React, JSX and Components: The Page as a Function of Data
  • React Props and Composition: Data Down, Calls Up, Children in the Slot
  • Routing With React Router: One Page, Many Addresses
  • React Component Tests With Vitest and Testing Library: Test What the User Sees
  • End-to-End Tests for a React App With Playwright: A Full Dress Rehearsal
  • Why AI-Built Websites All Look the Same, and Four Levels That Fix It
  • Visual Hierarchy, Spacing and the 8-Point Grid: Tell the Eye What to Read First
  • Colour, Contrast and Dark Palettes: 60-30-10, Semantic Tokens and Ratios You Can Compute
  • Typography That Sells: Type Scale, Line Length and Free Font Pairings
  • The UI Element Catalogue: Buttons to Toasts, Their Jobs, States and shadcn/ui Names
  • Design Tokens: Primitive and Semantic Tokens, from Figma to CSS to Tailwind
  • Tailwind CSS 4 in React: Utility Classes, Responsive Prefixes, Hover and Dark Mode
  • shadcn/ui in React: Components You Own, Edit and Commit
  • Design Tokens to a Tailwind Theme: Light and Dark Mode with @theme inline
  • Motion in React: Entrance, Hover, Exit and Layout Animations
  • A React Dashboard: Stat Cards, a Recharts Line Chart and a Sortable Table
  • Accessibility in Practice: Dialogs, Menus and the Keyboard in React
  • Reference-Driven Design: Extract a DESIGN.md From a Site You Admire and Build From It
  • Components, Variants and Variables: One Design System in Figma and in CSS
  • Figma MCP Server: Build a React Component From a Frame, Then Write It Back
  • Claude Design: From a Brief to a Clickable Prototype, Then Hand It Off to Claude Code
  • Critiquing AI-Generated UI: Six Checks for Every Screen
  • The AI Design Landscape: Prompt to UI, Prompt to App, and Design to Code
  • Your Brand Rules Folder: One Folder Every AI-Built Page Follows
  • The Best-Practice UI Prompt: Plain Sentences That Beat the Average AI Page
  • UI Ideas From Figma Make, Google Stitch and ChatGPT: One Prompt, Three Designs
  • Google Stitch From a Sketch or Screenshot: Show the Layout, Say What to Keep
  • Stitch to Figma to Code: Turn a Stitch Screen Into Code That Uses Your Tokens
  • Figma Make: Prompt to Prototype With a Four-Part Prompt
  • Upgrade a Dated UI From One Screenshot (or a Reference Image)
  • States and Feedback: Make Every Click Get an Answer
  • A Design-Loop Skill: Claude Screenshots, Scores and Fixes Its Own UI
  • Copy Without the AI Tells: A Copy Pass on a Landing Page
  • React State, Events, Lists and Conditional Rendering: Follow One Click
  • React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
  • Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
  • Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
  • React Context and Custom Hooks: Share One Value, Reuse the Logic
  • Server State With TanStack Query: One Key, One Request, One Cache
  • Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
  • Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
  • A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field
  • JWT Auth in a React Client With a FastAPI Backend: Log In, Carry the Token, Let the Server Decide
  1. Blog
  2. /
  3. React
  4. /
  5. Working with APIs

Server State With TanStack Query: One Key, One Request, One Cache

Three components need the same list of books. Fetch it by hand and you get three requests; ask TanStack Query for one key and you get one. With real request counts, retries and a quiet refetch on tab focus.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Working with APIs

What you will learn

  • Explain why data from a server is different from state you own
  • Share one cached list between components with useQuery and a query key
  • Read isPending, data and error, and see why fetch needs res.ok
  • Predict when TanStack Query sends a request: missing, stale or a retry

Before you start

  • React components, props and useState
  • async/await and fetch in JavaScript

Some state is yours. The author a user picked in a filter lives in your component, and nobody else knows about it. Other state is borrowed: a list of books lives on a server, and your page only holds a copy. That copy can get old, the server can be down, and three parts of the page may all want it at once.

This article follows one request for that list through a small library app and shows how TanStack Query keeps one shared copy of it. Every count and timing below comes from a real run of the project in Chrome.

One page, three parts, one list

The library app in the browser: the heading Library, the text 12 books, a row of author buttons starting with All authors, Frank Herbert and Jane Austen, and a list of books starting with Children of Dune, Dune and Dune Messiah, each with its author and page count.
The page: BookCount on top (12 books), AuthorFilter with seven buttons, and BookList with twelve rows.

Each part is its own component, and each one needs the books. The count needs them to count, the filter needs them to know which authors exist, and the list needs them to draw rows. All three want the same thing from the same address, GET /api/books. Who should fetch it, and how often?

One request, one JSON answer

Start with a plain function in src/api.ts. Nothing in it knows about React yet.

// Our one hand-written server call. Every screen
// part reuses it through the query cache.
export type Book = {
  id: number
  title: string
  author: string
  pages: number
}

export type BookPage = {
  content: Book[]
  page: { totalElements: number }
}

export async function getBooks(): Promise<BookPage> {
  const res = await fetch('/api/books?size=50')
  // fetch only throws on network errors, so we
  // turn a 4xx or 5xx answer into an error here
  if (!res.ok) throw new Error(`HTTP ${res.status}`)
  return res.json()
}

getBooks sends one GET to the Book API (a FastAPI app on port 8080; the Vite dev server forwards /api to it). The answer is JSON with a content array of books and a page object. Without size=50, this API sends five books a page, three pages in all, so the query string asks for all twelve at once. res.json() turns the text into a BookPage object.

fetch does not throw on a 404

Lines 17 to 19 matter more than they look. fetch rejects only when there is no answer at all, for example when the network is down. If the server answers with any status, 200, 404 or 500, fetch resolves. Here is a real 404 from the same API:

GET /api/books/99  ->  404
Content-Type: application/problem+json
{"detail":"No book with id 99","instance":"/api/books/99","status":404,"title":"Book not found"}

fetch did not throw here; res.ok is simply false. So getBooks throws its own Error(`HTTP ${res.status}`). Now a 404 fails the same way a dead network does, and that is what lets TanStack Query retry it and show an error.

The hand-made way: every component fetches for itself

Many apps start with a small hook like this one:

import { useEffect, useState } from 'react'
import { getBooks, type BookPage } from '../api'

// The hand-made way: every component that calls this
// hook fetches on its own and keeps its own flags.
export function useBooksByHand() {
  const [data, setData] = useState<BookPage>()
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  useEffect(() => {
    getBooks()
      .then(setData)
      .catch((e) => setError(e.message))
      .finally(() => setLoading(false))
  }, [])

  return { data, loading, error }
}

Each component that calls it gets three pieces of state and its own useEffect. Put it in BookCount, AuthorFilter and BookList, and one page load sends three GET requests to /api/books. You end up with three copies of the same twelve books and nine flags, and each copy can go out of date on its own.

Fetching is the easy part. Sharing one answer, and keeping it fresh, is the hard part.

A cache in the middle

Three components share one cache entry BookCount AuthorFilter BookList Query cache key ['books'] success, 12 books one QueryClient Book API :8080 1 GET
Same key, same entry. The first component to ask makes the entry and starts one request; the other two join it and wait for the same answer.

The idea is a box between the components and the server: a query cache. A component asks for data by name, and that name is the query key, here ['books']. If the cache has no entry for the key, it creates one, marks it pending and sends one request. When the other two components ask for the same key, nothing new goes to the server. When the JSON comes back, the entry switches to success and every component that asked renders with the data.

Where the cache lives

import { createRoot } from 'react-dom/client'
import {
  QueryClient,
  QueryClientProvider,
} from '@tanstack/react-query'
import './index.css'
import App from './App'

// the cache lives in this one object
const queryClient = new QueryClient()

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

new QueryClient() is the one object that holds every query in the app. QueryClientProvider wraps App, so every useQuery call below it reaches the same client.

useQuery, step by step

import { useQuery } from '@tanstack/react-query'
import { getBooks } from './api'

type Props = { author: string }

export default function BookList({ author }: Props) {
  const { data, isPending, error } = useQuery({
    queryKey: ['books'], // the name of this data
    queryFn: getBooks,
  })
  if (isPending) return <p>Loading books...</p>
  if (error) return <p>{error.message}</p>

  const books = data.content.filter(
    (b) => !author || b.author === author,
  )
  return (
    <ul>
      {books.map((b) => (
        <li key={b.id}>
          <span>{b.title}</span>
          <small>{b.author}, {b.pages} pages</small>
        </li>
      ))}
    </ul>
  )
}
  1. When BookList renders, useQuery takes the key ['books'] to the cache. On the first render there is no entry, so the cache makes one: status pending, data undefined.
  2. queryFn: getBooks hands the function over without calling it. The cache calls it, and the request leaves.
  3. On that first render isPending is true, so line 11 returns Loading books....
  4. The answer arrives (the request took 17 ms in the run, and the list was on screen 216 ms after the page started loading). The entry switches to success, BookList renders again, and lines 14 to 25 draw twelve rows: Children of Dune, Dune, Dune Messiah and the rest.

Line 12 is the other branch: if the query fails, error is set and the page shows error.message.

Same key, no second request

import { useQuery } from '@tanstack/react-query'
import { getBooks } from './api'

export default function BookCount() {
  // same key as BookList: same data, no new request
  const { data } = useQuery({
    queryKey: ['books'],
    queryFn: getBooks,
  })
  if (!data) return <p className="count">...</p>
  const total = data.page.totalElements
  return <p className="count">{total} books</p>
}

// BREAK IT: queryKey: ['book-count'] would make
// this component fetch the books a second time

BookCount uses the same key, so the cache already has the entry and sends nothing new. It reads data.page.totalElements, which is 12. The comment at the bottom is the classic mistake: give it its own key, ['book-count'], and to the cache that is a different entry with its own request. In the run, that change made the page send two GET requests instead of one.

Ours, and borrowed

import { useState } from 'react'
import AuthorFilter from './AuthorFilter'
import BookCount from './BookCount'
import BookList from './BookList'

export default function App() {
  // only the choice lives here, not the books
  const [author, setAuthor] = useState('')

  return (
    <main>
      <h1>Library</h1>
      <BookCount />
      <AuthorFilter
        value={author}
        onChange={setAuthor}
      />
      <BookList author={author} />
    </main>
  )
}

The chosen author sits in useState. That is client state: we own it and the server knows nothing about it. The books are server state: they live on the server and we hold a borrowed copy in the cache. When the user clicks Jane Austen, BookList filters the cached list down to three rows (Emma, Persuasion, Pride and Prejudice) and sends zero new requests.

When the API is down

For this test nothing was listening behind the dev server, so every request got a 502. The first attempt fails and getBooks throws. The page does not show the error yet. TanStack Query retries three times, waiting longer each time, and the page keeps saying Loading books... because the query is still pending:

api down: GET /api/books x 4 at 164, 1195, 3212, 7222 ms, status 502, 502, 502, 502
api down: "Loading books..." at 155 ms; "HTTP 502" at 7227 ms

Only after the fourth failure does the status become error, and line 12 shows HTTP 502, about 7.2 seconds after the first try.

A quiet refetch on tab focus

Someone else can add a book while your page is open. By default staleTime is zero, so the cached list is stale the moment it arrives. Stale does not mean wrong or gone. Stale data stays on screen; it just means "check again at the next good moment".

One good moment is when the tab gets focus again. In the run, switching back to the tab sent one quiet GET in the background. The text Loading books... did not come back and all twelve rows stayed on screen. Focusing again one second later sent one more request, because the data was already stale again.

Requests, counted

SituationGET /api/books
Hand-made hook in three components3
useQuery, one key ['books']1
BookCount with its own key ['book-count']2
Click an author filter0
Tab gets focus again1 more
API down4 (one try, three retries)

A request goes out only when the data is missing or stale, or to retry a failure.

Common mistakes

  • Trusting fetch to fail on a 404. It resolves. Check res.ok and throw, or your error branch never runs.
  • Two keys for the same data. A different key is a different cache entry and another request.
  • Copying server data into useState. Keep your own choices (the selected author) in state and leave the books in the cache.
  • Calling the function in queryFn. Pass getBooks, not getBooks(); the cache decides when to call it.

Quick recap

IdeaIn the code
One cache for the whole appnew QueryClient() inside QueryClientProvider
Ask for data by nameuseQuery({ queryKey: ['books'], queryFn: getBooks })
First render, then dataisPending true, then data holds the books
Errors only after retriesthree retries, then error is set
Stale data stays on screenquiet refetch on tab focus

Try it yourself

Change the key in BookCount.tsx to ['book-count'], open the browser's Network tab and count the requests to /api/books. Then put it back and watch the count drop to one. When you're ready to change data on the server, the next step is mutations and optimistic updates.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in React · 53 of 59

Previous
React Context and Custom Hooks: Share One Value, Reuse the Logic
Next post
Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache

Add a book with useMutation and let invalidateQueries refetch the list, then make delete instant: snapshot, remove the row in 3 ms, roll back on a 404 and refetch the truth in onSettled.

Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval

Let the API's OpenAPI spec write your React client: Orval turns /v3/api-docs into TypeScript types, useGetBooks and a Zod schema, and a renamed field becomes error TS2339 at BookList.tsx line 26.

A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec

Build the React screen before the API exists: Orval writes MSW handlers and faker data from the spec, a service worker answers GET /api/books inside the browser, and npm run dev:real switches back to the real server.

A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy

Generate a React client from FastAPI's /openapi.json, then hit the CORS wall: the API answers 200 but the browser blocks it. Fix it with CORSMiddleware, or avoid it with the Vite proxy and one VITE_API_URL variable.

On this page

  • One page, three parts, one list
  • One request, one JSON answer
  • fetch does not throw on a 404
  • The hand-made way: every component fetches for itself
  • A cache in the middle
  • Where the cache lives
  • useQuery, step by step
  • Same key, no second request
  • Ours, and borrowed
  • When the API is down
  • A quiet refetch on tab focus
  • Requests, counted
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.