Caching across the stack

Every cache from component to CDN, and how to invalidate each.

Builds on Caching in Next.js, Server state, The React Compiler.

"How would you cache a React app?" is one of the most common senior frontend interview questions, and one of the easiest to answer badly. The weak answer names one tool ("I'd use React Query" or "I'd wrap things in useMemo"). The strong answer starts by asking which cache, because a production React app has at least nine of them, from a memoized value inside one component to an edge server on another continent, and they differ in where they live, what they're keyed by and how they're invalidated.

You've met most of them already, one chapter at a time. This chapter lines them up, adds the HTTP and CDN layers that sit underneath every framework, and ends with an answer you can give out loud.

The problem: nine caches, one stale page#

A user adds a book to their reading list and the list doesn't show it. Where's the stale copy? It could be:

  • a useMemo whose dependency array missed the list,
  • a promise cached for use() that nobody cleared,
  • a TanStack Query entry that wasn't invalidated,
  • the Next.js client cache reusing the route's payload,
  • a service worker serving an old response,
  • the browser's HTTP cache honoring a max-age,
  • a CDN edge holding the page for its s-maxage,
  • a "use cache" entry on the server that wasn't tagged,
  • (not React cache(): that one can't be stale, because it dies with the request).

Debugging this, and designing it so it doesn't happen, needs one mental model that covers every layer.

Build it: the four questions#

Every cache, from useMemo to a CDN, is the same machine. You built several of them in this guide: a memo comparison in Chapter 29, a promise cache for use() in Chapter 26, a tagged cache with lifetimes in Chapter 48. Strip any of them down and you get four questions:

  1. Where does it live? One component instance, one request, one tab, one device, one region, every user. This decides who shares an entry, and whether sharing is a feature or a data leak.
  2. What's the key? The inputs that make two lookups the same. Too few inputs and users see each other's data; too many and nothing ever hits.
  3. How long is it fresh, and what happens after? Block and recompute, or serve stale and refresh in the background.
  4. How is it invalidated early? By time only, by an explicit call, by changing the key, or by throwing the whole cache away.

Here's that machine in its smallest form:

type Entry<V> = { value: V; storedAt: number };

function createCache<V>(maxAgeMs: number) {
  const entries = new Map<string, Entry<V>>(); // 1. where: this Map's owner
  return {
    get(key: string, compute: () => V): V {
      // 2. key: the caller decides
      const hit = entries.get(key);
      if (hit && Date.now() - hit.storedAt < maxAgeMs) return hit.value; // 3. freshness
      const value = compute();
      entries.set(key, { value, storedAt: Date.now() });
      return value;
    },
    invalidate: (key: string) => entries.delete(key), // 4. early invalidation
  };
}

Each real layer is this plus decisions about the four questions. Step through them:

Every cache in a React app
From the component outwardRender memoizationCached promise for use()TanStack Query cacheNext.js client cacheService workerBrowser HTTP cacheCDNNext.js "use cache"React cache()BrowserNetworkServerRender memoizationLives inA component instance (its fiber)Keyed byProps (memo) or a deps array (useMemo,useCallback), compared with Object.isInvalidated byAutomatically when an input changes.The React Compiler adds it for you.Taught in: Chapters 29 and 30
Step 1 of 9

Layer 1 of 9: Render memoization. In the browser. Every layer answers the same questions: where it lives, what it's keyed by, and how it's invalidated.

The layers, one by one#

1. Render memoization: memo, useMemo, useCallback and the Compiler#

Lives in a component instance (on its fiber). Keyed by props (memo) or a dependency array (useMemo, useCallback), each value compared with Object.is. Invalidated automatically whenever an input changes, and the entry is lost when the component unmounts.

const sorted = useMemo(() => [...books].sort(byTitle), [books]);

It saves CPU during re-renders, nothing else: no network, no sharing between components. The React Compiler inserts the equivalent automatically and more precisely than most hand-written code (Chapter 30). Its failure mode is the opposite of the others: not stale data but wasted work, when an input is a new object every render.

2. Cached promises for use()#

Lives wherever you put it, outside render: a module-level Map, a framework, a library. Keyed by whatever you choose, typically an id. Invalidated only when you delete or replace the entry.

const bookPromises = new Map<string, Promise<Book>>();

function getBookPromise(id: string) {
  if (!bookPromises.has(id)) bookPromises.set(id, fetchBook(id));
  return bookPromises.get(id)!;
}

function BookTitle({ id }: { id: string }) {
  const book = use(getBookPromise(id)); // same promise every render
  return <h2>{book.title}</h2>;
}

This cache exists for correctness, not speed: use() suspends on a promise, and if render created a new promise each time, the component would suspend forever (Chapter 26). The price is that you now own invalidation, which is exactly why libraries like TanStack Query exist.

3. React cache(): per request, on the server#

Lives for one server request. Keyed by the function's identity and its arguments (Object.is per argument, so pass primitives, not fresh objects). Invalidated by nothing: the whole cache is dropped when the request finishes.

import { cache } from "react";
export const getUser = cache(async (id: string) => db.user.find(id));

It deduplicates: the layout, the page and three components can all call getUser(id) and the database sees one query (Chapter 44). It can never serve stale data across requests, which is why it's the safe default for per-user data. Inside a "use cache" scope it's isolated, so don't use it to pass values into cached functions.

4. TanStack Query: the client cache for server data#

Lives in a QueryClient in browser memory, shared by every component in the tab. Keyed by the queryKey array (hashed). Freshness: data is fresh for staleTime (0 by default), then refetched on mount, window focus or reconnect while the old data stays on screen; unused entries are garbage-collected after gcTime (5 minutes). Invalidated with invalidateQueries, or updated directly with setQueryData for optimistic updates.

const mutation = useMutation({
  mutationFn: addBook,
  onSuccess: () => queryClient.invalidateQueries({ queryKey: ["books"] }),
});

Chapter 39 covers it. In Next.js, the server can prefill it per request through HydrationBoundary (Chapter 47). Its built-in behavior is stale-while-revalidate, the same idea that keeps coming back in this chapter.

5. Next.js "use cache" and the client router cache#

Lives in up to three places: the prerendered static shell (on disk or behind a CDN), a server cache (in memory per instance, or a remote handler with "use cache: remote"), and the browser (for the stale time). Keyed by the build ID, the function's identity and its serialized arguments. Freshness from cacheLife: stale, revalidate and expire. Invalidated with updateTag (immediately, for read-your-writes), revalidateTag(tag, profile) (stale-while-revalidate), revalidatePath, and every deploy.

async function getCatalog() {
  "use cache";
  cacheLife("hours");
  cacheTag("books");
  return db.book.findMany();
}

All of this is Chapter 48. Notice it's the only layer in the list with tags: you invalidate by what the data is, not by where it was rendered. On Next.js 14 and 15 without Cache Components, the same jobs are done implicitly by the Data Cache, the Full Route Cache and the Router Cache.

6. HTTP caching: Cache-Control, ETag and stale-while-revalidate#

Underneath every framework is HTTP, and the browser and every proxy between it and your server follow the response's headers. Lives in the browser's HTTP cache (private) and in shared caches like CDNs. Keyed by the URL, plus any request headers the response lists in Vary. Freshness and invalidation from Cache-Control:

DirectiveMeaning
max-age=60Fresh for 60 seconds, in any cache.
s-maxage=3600Overrides max-age for shared caches (CDNs) only.
stale-while-revalidate=300After it goes stale, a cache may serve it for 300 more seconds while refetching in the background.
no-cacheMay be stored, but must be revalidated with the server before every use.
no-storeMust not be stored at all.
privateOnly the browser may store it, never a shared cache. Use for anything personalized.
publicShared caches may store it, even for authenticated requests.
immutableWon't change while fresh: don't revalidate even on reload.

When a stored response goes stale, the browser doesn't have to download it again. If the response had an ETag (a version identifier the server chose), the browser sends If-None-Match: "<etag>", and if nothing changed the server answers 304 Not Modified with no body. Last-Modified and If-Modified-Since do the same with dates. Revalidation still costs a round trip; it saves the bytes.

Note what no-cache means. It's the most misnamed header on the web: it does cache, it just always checks first. To forbid storing, use no-store.

Build itWhat may a cache do with this response?

Implement decide({ cacheControl, age, shared }), which returns what a cache may do with a stored response that is age seconds old:

  • "no-store": don't use a stored copy at all (the response says no-store, or it's private and this is a shared cache).
  • "revalidate": must ask the server first (the response says no-cache, or it's too old).
  • "fresh": serve it as is.
  • "stale-while-revalidate": serve it, and refresh in the background.

Shared caches use s-maxage instead of max-age when it's present. parse is written for you. Press Check when ready.

// "max-age=60, stale-while-revalidate=300" -> { "max-age": 60, "stale-while-revalidate": 300 }
// Directives without a value ("no-cache", "private") map to true.
export function parse(cacheControl) {
  const out = {};
  for (const part of cacheControl.split(",")) {
    const [name, value] = part.trim().toLowerCase().split("=");
    if (name) out[name] = value === undefined ? true : Number(value);
  }
  return out;
}

export function decide({ cacheControl, age, shared = false }) {
  const d = parse(cacheControl);
  // Only handles max-age so far.
  if (age < (d["max-age"] ?? 0)) return "fresh";
  return "revalidate";
}
Nothing logged yet.

7. The CDN#

A CDN is a shared HTTP cache on servers near your users. Lives at edge locations, shared by everyone who hits that edge. Keyed by URL by default, plus whatever headers or cookies you configure (be deliberate: keying on all cookies destroys the hit rate, ignoring a cookie that changes the response leaks data). Freshness from s-maxage and stale-while-revalidate. Invalidated by time, by a purge API call (by URL, or by tag on CDNs that support cache tags), or by a deploy.

This is where Next.js's static shell pays off. A prerendered page or shell can be served from the edge without touching your server, and the dynamic holes stream from your server inside the same response. On Vercel this is wired up for you; when self-hosting, Next.js sends Cache-Control headers based on each page's revalidation time, and your CDN must respect them (and must never cache a response that set a cookie or depends on one unless the key includes it).

8. Hashed static assets and immutable caching#

The cheapest invalidation is never needing one. Build tools put a content hash in every JavaScript, CSS and font filename: app-3f9a1c.js. If the content changes, the name changes, so the old file can be cached forever and the new one is simply a different URL. Next.js serves /_next/static/* this way, with a header like:

Cache-Control: public, max-age=31536000, immutable

The HTML that references those files is the opposite: it must stay short-lived or revalidated, because it's what tells the browser which hashes are current. Get that backwards (HTML cached for a year) and users run last month's app indefinitely. Since 16.3, Next.js can also reuse immutable assets across deployments, since a hashed file can't suffer from version skew.

9. Service workers#

A service worker is a script that sits between your page and the network and can answer requests from Cache Storage, an origin-scoped store on disk. Keyed by Request (URL and method). Freshness and invalidation are entirely your code: the usual strategies are cache-first (static assets), network-first (HTML and API data) and stale-while-revalidate, and old caches are deleted when a new worker version activates.

sw.js
const VERSION = "v42";

self.addEventListener("activate", (event) => {
  // Invalidation: drop every cache that isn't this version's.
  event.waitUntil(caches.keys().then((keys) => Promise.all(keys.filter((k) => k !== VERSION).map((k) => caches.delete(k)))));
});

self.addEventListener("fetch", (event) => {
  if (event.request.destination === "script" || event.request.destination === "style") {
    // Cache-first: hashed assets never change.
    event.respondWith(caches.match(event.request).then((hit) => hit ?? fetch(event.request)));
  }
});

They make offline support and instant repeat visits possible, and they're the most dangerous layer on this list: a buggy cache-first rule for HTML can pin users to an old version, and because the service worker itself controls updates, fixing it requires the browser to fetch a new worker. Use a library like Workbox, keep HTML network-first, and ship a kill switch.

Putting it together: the reading list#

Here's which layer serves which data in the Next.js reading list, and what happens when a user adds a book:

DataLayerKeyInvalidation
JS, CSS, fontsHashed static assets, browser cache and CDNURL with content hashA new hash on deploy
The book catalog"use cache" with cacheLife("hours"), part of the static shell, served from the CDNFunction plus argumentsupdateTag("books") in the add action; CMS webhook uses revalidateTag("books", "max")
A user's shelf"use cache" keyed by user id, inside SuspenseUser id argumentupdateTag("shelf-" + userId)
Session, current userReact cache()Per requestDies with the request
A live "recently read by friends" feedTanStack Query with polling["feed", userId]refetchInterval, invalidateQueries
A sorted copy of the shelfCompiler or useMemoIts inputsAutomatic

The write path: the Server Action updates the database, calls updateTag for the catalog and the shelf, and Next.js re-renders the route into the action's response, clearing the client router cache's prefetched routes. The CDN copy of the shell is refreshed when that page next regenerates. No layer is left holding the old list, because each one has a stated owner and a stated way to be invalidated.

A strong answer#

When the question comes, structure beats completeness. Something like this, in about a minute:

"I'd separate it by layer, because each one has a different key and a different way to go stale. In the component, memoization with memo and useMemo, or the React Compiler, just to avoid recomputing during re-renders; it's keyed by inputs and invalidates itself. For server data on the client, a query cache like TanStack Query: keyed by query key, stale-while-revalidate with a staleTime, and invalidated explicitly after mutations. On the server, React's cache() deduplicates within one request, and in Next.js I'd use "use cache" with cacheLife for shared data and tags, so a mutation can call updateTag and the user reads their own write. Underneath that is HTTP: hashed static assets with a one-year immutable Cache-Control, short-lived or revalidated HTML with ETags, s-maxage and stale-while-revalidate for what the CDN can share, and private for anything personalized. Service workers only if we need offline. For every layer I'd want to answer where it lives, what it's keyed on, and who invalidates it, and I'd be most careful about anything shared between users."

Pitfalls#

Check your understanding#

PredictThe deploy nobody sees

A team self-hosts a React app behind a CDN. Every response, including index.html, gets Cache-Control: public, max-age=31536000, immutable. JavaScript files have content hashes in their names. They deploy a new version. What do returning users get, and what does the CDN do? What's the fix?

Quick checkWhich layer?

Three Server Components in one request each call getCurrentUser(). It reads the session and queries the database. Which cache should deduplicate it?

Quick checkSame idea, many layers

Which pair of mechanisms both implement stale-while-revalidate?

Explain it out loudHow do you cache a React app?

An interviewer asks the question directly: "How would you approach caching in a React application?"

Explain it out loudTrace a write

"A user adds a book and the list doesn't update. Walk me through how you'd find which cache is stale."

Interview angle

Say it in 30 seconds

A React app has many caches, and each answers four questions: where it lives, what it's keyed by, how long it's fresh, and how it's invalidated. Memoization and the React Compiler cache computations per component, keyed by inputs. TanStack Query caches server data in the browser by query key, with stale-while-revalidate and explicit invalidation. React cache() deduplicates within one server request, and Next.js "use cache" caches across requests with cacheLife and tags. Underneath, HTTP Cache-Control, ETags and CDNs cache responses, hashed assets are cached for a year as immutable, and service workers add an offline layer. Personalized data must never land in a shared cache.

How would you approach caching in a React application?

senior

What's the difference between Cache-Control no-cache, no-store, private and immutable?

intermediate

Why do build tools put hashes in asset filenames, and how should HTML be cached?

basic

What's the difference between React's cache() and Next.js "use cache"?

intermediate

A user writes data and still sees the old value. How do you find the stale cache?

senior

Recap#

  • Every cache answers four questions: where it lives, what it's keyed by, how long it's fresh, and how it's invalidated. Answer them for each layer instead of naming a tool.
  • In the browser: render memoization (inputs, automatic), cached promises for use() (you own invalidation), TanStack Query (query key, stale-while-revalidate, explicit invalidation), the Next.js client cache, service workers, and the HTTP cache.
  • On the server: React cache() for one request, and Next.js "use cache" across requests with cacheLife and tags.
  • HTTP ties it together: max-age, s-maxage, stale-while-revalidate, no-cache vs no-store, private, and ETags for cheap 304s. CDNs are shared caches, so personalized responses must be private.
  • Content-hashed assets get a one-year immutable header; HTML must stay revalidated. A write should invalidate the one layer that owns that data.

Sources#