What you'll learn: By the end of this lesson you will be able to explain why server data needs its own kind of state, describe a client-side query cache as keys, entries, observers and timers, choose
staleTime,gcTimeand refetch triggers for a screen, invalidate the right entries after a write, read the difference between "no data" and "fetching" in a UI, and tell what this layer adds on top of the browser's HTTP cache.
Imagine a photo of the departure board at a railway station. You took it a minute ago, and it is good enough to decide which platform to walk towards. Whether you trust it after ten minutes depends on how fast the board changes. If you and two friends each keep a photo, you hold three copies that can drift apart. If you share one photo and update it together, you hold one copy that you can label with its age.
A page that shows data from an API is in the same position. The server owns the data. The page holds a photo of it, and several components may hold the same photo. Somebody has to decide when a photo is good enough, when to take a new one, who shares it, and when to throw it away. That bookkeeping is server state, and a query cache is the component that does it.
The running example is a product page in an online store. It shows one product (name, price, stock), a related-products list that depends on the category and page, and a cart count in the header. Three components read the cart count. A "Save price alert" button writes to the server and should make the page correct afterwards. All lifetimes and sizes below are illustrative unless a source is named.
The core idea
Hold on to three statements.
- Server state is a copy of data you do not own. It can be out of date without your code knowing, it is shared between components, and it needs a loading story and an error story. State that lives only in the page (an open dropdown, a draft) has none of these problems.
- A cache for it makes four decisions: identity (which question does this entry answer: the key), freshness (how long the answer is trusted:
staleTime), lifetime (how long an unused answer is kept:gcTime), and refresh (what triggers a new request: a mount, a window focus, a reconnect, a timer, or an invalidation after a write). - Show what you have, refresh in the background, and say which of the two is happening. This is the stale-while-revalidate idea: serve the copy you hold now, revalidate it without blocking, and swap in the new answer when it arrives.
The examples use the vocabulary of TanStack Query, whose current documentation is the main source here, and compare it with SWR where the two differ. The names differ between libraries; the four decisions do not. A small model of such a cache, with tests and a captured trace, is the lab at the end.
Server state is not client state
A client state value, such as whether a menu is open, is created, owned and destroyed by the page. A server state value is a snapshot of something that lives elsewhere. Four consequences follow from that, and they are why teams stop putting API responses into a general-purpose store.
- It goes stale. Another user, another tab or a background job can change the real data at any time.
- It is asynchronous. There is a moment with no data, a moment with data being refreshed, and a moment when the refresh failed.
- It is shared. The header badge and the cart page ask for the same cart. Two requests and two copies would disagree.
- It must be updated by a protocol, not by assignment. After a write you cannot just set a variable; you must refresh or patch the snapshot you hold.
Putting responses into a hand-written store means rebuilding all four, once per endpoint. A query cache does it once. The lesson on local versus global state covers where client state should live; this lesson is about the other half.
Where this sits next to the HTTP cache
The browser already has a cache, covered in HTTP Caching for the Front End. It stores responses by URL and request headers and obeys Cache-Control. A query cache is a second, separate layer, written in JavaScript and living in memory:
| Browser HTTP cache | Application query cache | |
|---|---|---|
| What it stores | HTTP responses (bytes, headers) | The values your query functions returned (parsed data) |
| Identity | URL plus Vary headers |
A key you choose (an array such as ["products", 1234]) |
| Who decides freshness | The server, through Cache-Control |
Your code, through staleTime and friends |
| Who can read it | Any request the browser makes | Components subscribed to the key |
| Knows about your writes | No | Yes: you invalidate or patch entries |
| Survives a reload | Yes, subject to its rules | No, unless you persist it yourself |
They stack. When a query function calls fetch, that request still passes through the HTTP cache beneath it, so a stale entry in the query cache can be refilled from a fresh HTTP-cache hit, or from a 304. Keep both in mind when you tune: a long staleTime removes the request, while a long max-age only makes the request cheap. The whole stack, from CDN to component, is the subject of the lesson on caching across the stack.
Figure 1. Components, the query cache and the HTTP cache
How to read this: components do not call the API. They subscribe to a key. The query cache decides whether to answer from memory, and only when it needs new data does it call fetch, which the HTTP cache may still answer.
Query keys: the identity of an answer
A query key names the question an entry answers. TanStack Query's guide says keys are top-level arrays that can be serialised with JSON.stringify, and that they are hashed deterministically: the order of properties inside an object does not matter, but the order of array items does. Its guidance is that a key should include every variable your query function uses that changes, so a changed variable becomes a different entry.
Illustration 1: a minimal example.
["products", 1234] // one product
["products", { category: "shoes", page: 1 }] // one page of a list
["products", { page: 1, category: "shoes" }] // the same entry as the line above
["products", 1234] vs [1234, "products"] // different entries: array order counts
Two components that ask for ["products", 1234] are asking the same question, so they share one entry. That sharing is the point. It also means a key is a contract: if two different questions produce the same key, they will be handed each other's answers.
Illustration 3: a failure case, the key that forgets a variable. A to-do list screen filters its items with a filter variable, but its key is just the list name with no variable. The lab's test renders two screens, one with filter "all" and one with "done", on that same key with a long staleTime. The second screen is handed the data for "all": the entry exists, it is fresh, so no request is made for "done". Putting the variable in the key (the list name plus { filter: "done" }) gives each screen its own entry. This bug is silent: nothing throws, the UI shows plausible data for the wrong question.
Keys also have a second job. Because invalidation matches by prefix, a good key is a path from general to specific. ["products"] matches every product entry, ["products", { category: "shoes", page: 1 }] matches one page. Design the hierarchy for the invalidations you will need, not only for the reads.
An entry has two independent questions
Each entry reports two separate facts, and mixing them up is the most common UI bug in this area.
statusanswers "do we have data?" It ispending(no data yet),success(data is available) orerror(the fetch failed).fetchStatusanswers "is the query function running?" It isfetching,idle, orpaused(the query wanted to fetch but could not, for example without a network).
TanStack's guide explains why both exist: background refetches and stale-while-revalidate make every combination possible.
status |
fetchStatus |
What it means on the product page | What to render |
|---|---|---|---|
pending |
fetching |
First visit, request in flight | A skeleton or spinner |
success |
idle |
Data present, nothing running | The data |
success |
fetching |
Data present, a refresh is running | The data, optionally a subtle "updating" cue |
error |
idle |
The last request failed | An error state (and the data, if any was kept) |
pending |
paused |
No data and no network | An offline message, not a spinner forever |
A component that renders a spinner whenever something is fetching will flash the whole page on every background refresh. A component that only checks status shows stale data without telling anyone. Use status for "what do I show" and fetchStatus for "should I hint that it is refreshing".
Freshness: staleTime
Data in an entry is fresh for staleTime milliseconds after it arrives, then stale. TanStack's documentation gives the default as 0, so by default cached data is stale as soon as it is stored. Stale does not mean wrong or discarded; it means "worth re-checking when something gives a reason to". You can set staleTime to Infinity (never stale), and the reference also lists a "static" value with the same effect.
What does stale data cause? On the next trigger, a refetch runs in the background while the cached data is still shown. The documented triggers are: a new instance of the query mounts, the window is refocused, and the network reconnects. Each can be turned off with a matching option, and refetchOnMount and refetchOnWindowFocus default to true, meaning "refetch if the data is stale". SWR revalidates on focus and on reconnect by default, and on a timer only if you set refreshInterval; its API page also lists throttles: its API page lists dedupingInterval = 2000 ms and focusThrottleInterval = 5000 ms as defaults.
Staleness is judged per observer in the lab's model: the same data can be fresh for a component that asked for a long staleTime and stale for one that asked for none. This follows from staleTime being an option of the observer, not a property of the data.
Figure 2. What happens when a component asks for a key
for this key?"} B -->|"no"| C["Create entry: pending
start a fetch"] B -->|"yes"| D["Join entry, show its data now"] D --> E{"Stale for this
component, or invalidated?"} E -->|"no"| F["Done: no request"] E -->|"yes"| G["Background fetch
(fetchStatus: fetching)"] C --> H["Response lands: success
all subscribers update"] G --> H
How to read this: the only path that shows a loading state is the first one. Every other mount shows data immediately, and the only question is whether to refresh it.
Stale-while-revalidate, and how it relates to the HTTP header
The name comes from an HTTP idea. RFC 5861 defines a stale-while-revalidate Cache-Control extension: a cache MAY serve a stale response for the stated number of seconds, and SHOULD try to revalidate it without blocking. Its example is Cache-Control: max-age=600, stale-while-revalidate=30: fresh for 600 seconds, then usable stale for up to 30 more while a check runs. SWR's site says its name "comes from stale-while-revalidate".
The two layers apply the same shape with different rules. The header has a bounded stale window and is applied by a cache that obeys the origin's directive. A query cache keeps showing the entry until it is garbage collected, and your code chooses the triggers. Do not assume that setting one configures the other.
Figure 3. A later visit: cached data first, new data after
How to read this: the user never sees a spinner on this path. What they might see is the old price for the length of one round trip, which is the price of an instant screen.
Lifetime: gcTime
When the last component using an entry unmounts, the entry becomes inactive. It is not removed straight away: a timer of gcTime starts. TanStack's guide says unused entries are garbage collected after 5 minutes by default, and the reference lists 5 * 60 * 1000 ms, or Infinity during server-side rendering, with Infinity disabling collection. If a component mounts the key before the timer ends, the entry is reused and the timer is cancelled; if not, the entry and its data are deleted, and the next mount starts again from pending.
This is why navigating away and straight back is instant, while coming back an hour later shows a loading state. It is also a memory control: an app that visits thousands of distinct keys (search results, pages of a feed) keeps only recent ones.
staleTime and gcTime are independent. A common confusion is to expect a long gcTime to keep data fresh. It only keeps data around, and with the default staleTime the kept data is refetched on its next use.
Figure 4. The life of one entry
first fetch"] --> S["success
fresh for staleTime"] S --> ST["success, stale
refetch on next trigger"] ST -->|"trigger: mount, focus,
reconnect, invalidate"| S S -->|"last component leaves"| I["inactive
gcTime timer runs"] ST -->|"last component leaves"| I I -->|"component returns
before gcTime"| S I -->|"gcTime elapses"| D["deleted"]
How to read this: an entry cycles between fresh and stale while it is in use. Leaving only starts a countdown; it is a return visit inside the countdown that makes navigation feel instant.
Sharing and deduplication
Every component that uses a key joins one entry, so when a response arrives all of them update together. TanStack's guide describes this: instances with the same key share a status and receive new data together. The lab's model goes one step further as its own rule: while a request for an entry is in flight, another component that needs the same entry gets the same request, so the header badge and the cart page cause one call, not two. SWR documents the same intent with its dedupingInterval: requests with the same key inside that window are deduplicated. The TanStack pages read for this lesson do not state the rule in those words, so check your library's documentation before relying on it.
Invalidation: after a write
When you change data on the server, the entries that depend on it are now wrong. Invalidation says so: it marks matching entries stale, and TanStack's guide adds that entries currently used by a mounted component are also refetched in the background. Three details matter.
- Matching is by key prefix. Invalidating
["products"]matches["products", { page: 1 }]too. Theexactoption limits the match to the one key. - Invalidation overrides
staleTime. The guide states the stale state set this way overrides thestaleTimeof any hook. A write is always a good reason to refetch. - Unused entries are marked, not fetched. The guide describes the refetch only for entries being rendered. In the lab's model, an entry nobody uses is marked and refetched on its next use, even with a long
staleTime. That is the model's choice, consistent with the guide's wording, not a quoted guarantee.
An alternative to refetching is patching: the mutation's response is written straight into the entry (TanStack's guide for this is "updates from mutation responses", using setQueryData, and warns not to mutate the cached object in place). Patching saves a round trip but only works if the response is the whole new value; invalidation is the safer default when the server computes things you cannot predict.
Illustration 2: a realistic example. On the product page, saving a price alert is a write. The figure shows what the cache does next.
Figure 5. A write, then invalidation
list page 2 (nobody uses it): stale, wait Q->>S: GET product 1234 S-->>Q: product with alert flag Q-->>C: update
How to read this: one prefix reached both entries, but only the one on screen costs a request. The other pays on its next visit.
Tying it to React
A cache lives outside React, so a component needs a way to subscribe. React's useSyncExternalStore(subscribe, getSnapshot) is made for this, and its documentation sets two rules the cache must respect. First, getSnapshot must return the same value while the store has not changed, and a different one when it has (compared with Object.is); a function that builds a new object on each call is the documented mistake. So an entry exposes one result object and replaces it only on a change. Second, if you pass a different subscribe function on a re-render, React re-subscribes; the documentation suggests defining it outside the component or wrapping it in useCallback. The hook in the lab keeps subscribe stable for as long as the key's hash is unchanged. Subscribing is also what starts the first fetch, which is why "mount" is the trigger.
Errors and retries
An entry can fail while holding data. TanStack's defaults say failing queries are silently retried 3 times with exponential backoff before the error surfaces. Two points an architect should still decide: the query function must throw on a bad response (its guide notes that fetch does not throw on HTTP error statuses), and a failed refresh should not erase good data. In the lab's model an error keeps whatever data the entry had, so the UI can show the old data with a "could not refresh" note instead of a blank error page. That is again the model's choice; verify it in the library you use.
Trade-offs
| Decision | Leans towards | Cost |
|---|---|---|
Short staleTime (default 0) |
Freshness; every mount and focus can refetch | More requests; "flicker" of values changing under the user |
Long staleTime |
Fewer requests, instant screens | The user may see old data; needs invalidation after writes |
Long gcTime |
Instant return visits | Memory held, stale data kept longer |
| Refetch on focus | Correct after a tab switch | Bursts of requests when users switch tabs; costs on slow APIs |
| Invalidate after a write | Simple and correct | One extra read per write |
| Patch from the response | Instant, no extra read | Easy to get out of step with what the server really stores |
| Fine-grained keys | Reuse and precise invalidation | More entries; more invalidation bookkeeping |
| Coarse keys | Few entries | One change refetches too much; wrong-key bugs |
Build it: watch a cache model run
Goal. See, step by step on a fake clock, the rules above: two components sharing one request, a fresh hit that causes no request, a window-focus refetch of stale data, an invalidation, and an unused entry being removed after gcTime.
Setup. The lab lives in the course's example workspace. It needs Node.js (the trace was captured on Node 26.13.1, which runs TypeScript files directly) and pnpm. The model is about 200 lines in src/cache.ts; a small useQuery hook in src/react.tsx binds it to React with useSyncExternalStore.
cd examples/frontend
pnpm install
pnpm --filter ./labs/query-cache-model test # 30 tests: 24 on the model, 6 on the React hook
cd labs/query-cache-model
node src/demo.ts # prints the trace below
Steps.
- Read the demo's setup line:
staleTimeis 30 seconds andgcTimeis the 5-minute default. Before reading the output, predict how many requests the whole timeline sends. - Find the two components that mount at t=0. Only one "request #1 sent" line appears, and the state line shows
observers=2. - At t=10 a third component mounts. The data is 10 seconds old, inside the 30-second window, so no request is sent.
- At t=31 the window regains focus. The data is 31 seconds old, so a refetch runs. Compare with t=10.
- At t=36 a save "succeeds" and the cache invalidates
["cart"]. The state line showsfetchStatus=fetchingwhile the old data is still present, andinvalidated=true. The longstaleTimedid not stop it. - After all three components unmount, the entry survives until t=336, which is 5 minutes after t=36. The timeline ends with
total requests sent: 3.
Expected output, captured from a real run (Node 26.13.1, 2026-11-30):
Query cache model: staleTime 30 s, gcTime 5 min (the default)
t= 0s component A mounts (new key)
t= 0s request #1 sent
t= 0s component B mounts while A's request is in flight (same key)
t= 0s state: status=pending fetchStatus=fetching data=undefined observers=2 invalidated=false entries=1
t= 0s response lands -> status=success fetchStatus=idle data="v1"
t= 10s component C mounts, data is 10 s old (fresh)
t= 10s state: status=success fetchStatus=idle data="v1" observers=3 invalidated=false entries=1
t= 31s window focus; data is 31 s old, stale for A: true
t= 31s request #2 sent
t= 31s response lands -> status=success fetchStatus=idle data="v2"
t= 36s a save succeeds -> invalidate(['cart'])
t= 36s request #3 sent
t= 36s state: status=success fetchStatus=fetching data="v2" observers=3 invalidated=true entries=1
t= 36s response lands -> status=success fetchStatus=idle data="v3"
t= 36s all three components unmount
t= 36s state: status=success fetchStatus=idle data="v3" observers=0 invalidated=false entries=1
t=335s 1 s before gcTime
t=335s state: status=success fetchStatus=idle data="v3" observers=0 invalidated=false entries=1
t=336s gcTime reached
t=336s entry exists: false, entries=0
total requests sent: 3
This is a model, not the library. The lab follows the rules the documentation describes and says in its source where a behaviour is its own choice: it has no retries, no structural sharing, no cancellation, no network mode and no pagination, and what it does when invalidated mid-flight, or when a refresh fails, is the lab's decision. The tests run under jsdom, a JavaScript model of the DOM, so nothing here shows how a real browser, a real network or a real library behaves.
Break it. In src/cache.ts, in isStale, delete the line entry.invalidated ||. Run the tests: one test fails, "an entry nobody uses is marked stale but not fetched, and refetches on its next use despite a long staleTime", because an invalidated entry that nobody uses now looks fresh under the long staleTime. Restore the line and run the tests again.
Stretch. Pick one:
- Add
refetchIntervalto the model (a timer on the fake clock that refetches while an entry has observers) and test that it stops when the last observer leaves. - Add
setQueryDataand test that patching the entry notifies observers without a request. - Make staleness depend on a per-key default, as a "defaults by key prefix" table, and test which wins when an observer also passes its own value.
In practice: a product page that is either stale or slow
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
An online store's product page loads its product, related products and the cart count with a hand-written useEffect and useState in each component. Three problems appear in the product team's tracker. The header badge and the cart page each request the cart on every mount, so the cart API sees duplicate calls (illustratively, about two per page view). Going back to a product from the list shows a spinner every time, even though the user was there seconds ago. And after "Save price alert", the page still shows the old state until the user reloads. Five engineers own the page. Some pages are visited thousands of times per hour, and some are almost never visited.
Starting architecture
Figure 6. Every component fetches for itself
How to read this: three copies, three requests, no shared memory. Each warning box repeats loading, error and refresh logic of its own.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Put API responses in the global store | One copy | Hand-written loading, staleness, invalidation per endpoint | Stale data with no expiry rule; every endpoint reimplemented |
| Rely on HTTP caching alone | Cheap repeat requests | Still one request per mount, still a spinner | Cannot invalidate after a write from the page |
| Adopt a query cache library | Keys, sharing, expiry, invalidation in one place | A new dependency and a concept to learn | Wrong keys or lifetimes cause quiet staleness |
| Server-side rendering with a client fetch layer | First paint with data | More moving parts | Must hydrate the cache correctly |
The decision
| Field | Decision record |
|---|---|
| Context | Duplicated requests, spinners on revisit, and stale state after writes, all from per-component fetching. |
| Decision | Adopt a query cache. Keys are ["cart"], ["products", id] and ["products", { category, page }], defined in one module. Cart: staleTime 0. Product: staleTime 60 s (illustrative). After the price-alert write, invalidate ["products"]. |
| Consequences, good | One request per key at a time; instant revisits; the page is correct after writes; loading and error states are uniform. |
| Consequences, bad | Keys become a shared contract; a long staleTime can show an old price for up to a minute. |
| Revisit when | Field data shows users acting on stale prices, or the API cost of focus refetches grows. |
Rollout and verification
- Centralise keys first in one module and write a test that every query function's variables appear in its key.
- Migrate one screen (the cart badge, which is shared) and compare request counts per page view before and after.
- Check the stale-price risk with the business: decide which fields may be 60 seconds old, and which must always be refetched (stock at checkout).
- Test the write path: save an alert, confirm the product entry refetches, and confirm an unused list entry is only marked stale.
The 2 a.m. failure
A support ticket says the product page for one category shows the wrong prices after the user changes the sort order. The list query's key is ["products", { category }], but its query function also sends sort. Because sort is not in the key, a new sort order maps to the same fresh entry and no request is made. The bug is exactly the silent wrong-key case shown earlier, and it escaped review because nothing errors.
First three checks: (1) compare the request in the network panel with the key in the devtools: is a variable missing from the key; (2) check whether the entry was fresh (staleTime hides the bug until it expires); (3) search the module for query functions that read variables not in their key. Mitigation: add sort to the key and deploy; the old entries are never read again and expire after gcTime. Follow-up: a lint rule or a test that derives the key from the same object the query function uses, so they cannot drift.
Architect's notes
- Make keys a design artefact. One module defines every key, as a hierarchy that mirrors the invalidations you need.
- Pick
staleTimeper data type, not per screen. A price list, a cart and a user profile have different tolerances. Write them down next to the key. - Remember what a long
staleTimecosts. It saves requests and hides changes, so every long value needs an invalidation story. - Render from
statusand hint withfetchStatus. Do not flash spinners on background refreshes. - Do not mirror query data into local state. A copy in
useStatestops following the cache. - Treat the cache as a performance layer, not the system of record. It is wiped on reload and can be wrong; money and permissions are checked on the server.
Common mistakes
- Leaving a variable out of the key. Two questions share one entry and one answers the other.
- Treating
gcTimeas freshness. It controls memory, not trust. - Copying query data into
useState. The copy never updates. - Rendering a spinner on every fetch. Background refreshes flash the screen; show a spinner only when there is no data.
- Forgetting to throw on a bad HTTP status.
fetchdoes not throw for 404 or 500, so the cache stores an error body as success. - Invalidating too broadly or too narrowly.
[]refetches the world; an exact key misses the list that shows the changed item. - Assuming the cache survives a reload or is shared between tabs. It is per page load unless you add persistence.
Key takeaways
- Server state is a snapshot of data owned elsewhere: it goes stale, is asynchronous, is shared, and is updated by refetching or patching.
- A query cache is entries identified by keys; components subscribe, and entries are shared and updated together.
statussays whether you have data;fetchStatussays whether a request is running; both can vary independently.staleTime(default 0 in TanStack Query) decides when cached data should be re-checked;gcTime(5 minutes by default for unused entries) decides when it is deleted.- Stale data is shown immediately and refreshed in the background on a mount, a window focus or a reconnect: stale-while-revalidate.
- Invalidation marks entries stale by key prefix, overrides
staleTime, and refetches those in use. - The query cache sits on top of the HTTP cache: it adds keys, sharing and write-awareness, and does not replace
Cache-Control.
Practice exercises
Exercise 1 — Starter (30 min): For a product page, write the query keys for: one product, a filtered and paginated product list, and the cart. For each, name the one write that should invalidate it and the prefix you would pass.
Exercise 2 — Intermediate (2 hours): Run the lab's tests, then read test/cache.test.ts. Pick three tests and, for each, change the numbers in the model's inputs (not the model) to see the boundary: a mount at exactly staleTime, a remount at exactly gcTime, and an invalidation of an entry nobody uses.
Exercise 3 — Advanced (half day): Extend the model with a per-key staleTime table and a setQueryData that patches an entry. Write tests for the case where an invalidation arrives while a patch is in flight, decide what should happen, and document that as a model choice.
Related reading
In this course:
- HTTP Caching for the Front End — the browser's cache,
Cache-Controland validation, one layer below this one. - Caching Across the Front-End Stack — how browser, service worker, CDN and application caches fit together.
- React Hooks Internals — how hooks such as
useSyncExternalStoreare stored and re-run. - REST, GraphQL and tRPC for the Front End — the API styles whose responses end up in this cache.
Elsewhere on the site:
- System Design: Caching Basics — back-end cache layers and what not to cache.
- System Design: Advanced Caching — stampedes and invalidation on the server side.
Official documentation
- TanStack Query: Important Defaults — stale by default, refetch triggers, the 5-minute
gcTime, retries. - TanStack Query: Caching — the lifecycle of an entry across mounts.
- TanStack Query: Query Keys and Query Invalidation.
- SWR: API options and Revalidation.
- RFC 5861: HTTP Cache-Control Extensions for Stale Content — where
stale-while-revalidatecomes from. - React: useSyncExternalStore.