Skip to content

Client caching and normalized stores

A client cache answers a repeated request from memory and can refresh it in the background; a normalized store keeps each record once, by ID, so one change reaches each screen. A strong answer states the freshness rule for both.

On this page

What it is

A client cache is a map in memory from a request key to the last answer for it. In RTK Query the key is the endpoint name plus its serialized arguments, so two components asking for the same thing with the same arguments share one entry and one request. Change an argument and you get a different key, which is why an autocomplete box should key on everything the server uses to answer, including filters and language, not just the typed text.

Two separate timers govern an entry. The first is freshness: how long an answer is served as-is before the cache treats it as stale. In TanStack Query v5 this is staleTime, and by default a cached answer counts as stale as soon as it lands. A stale entry is still shown; what changes is that a new component mounting with that key, the window regaining focus, or the network reconnecting triggers a background refetch. The second timer is garbage collection: an entry no component is using is kept for gcTime, 5 minutes by default, then dropped. RTK Query keeps an unused entry for keepUnusedDataFor, 60 seconds by default, and offers refetch on focus and on reconnect as options you switch on.

Serving the cached answer first and refreshing behind it is called stale-while-revalidate. The name comes from an HTTP Cache-Control extension in RFC 5861, which lets a cache return a stale response for a set number of seconds while it revalidates in the background. The SWR library takes its name from that RFC and describes the same loop for a React app: return what is in the cache, send the fetch, then hand the component the fresh data.

A normalized store treats client state like a small database. The Redux guide on normalizing state shape recommends giving each kind of record its own table, storing items in an object keyed by ID, keeping order in a separate array of IDs, and referring to a record from elsewhere by its ID rather than embedding a copy. Apollo Client 4's InMemoryCache does this automatically for GraphQL results: it splits each response into objects, gives each identifiable object a cache ID built by default from its __typename and its id or _id (a Post with id 42 becomes Post:42), replaces nested objects with references to those IDs, and merges fields when the same object arrives twice. When the cache can't build an ID for an object, it stores that object inside its parent instead.

ts
type Post = { id: string; authorId: string; likeCount: number; likedByMe: boolean };
type User = { id: string; name: string };

type Store = {
  posts: Record<string, Post>;
  users: Record<string, User>;
  feed: string[];            // order only; the records live in posts
  profileFeeds: Record<string, string[]>;
};

// One write; every view that reads post 42 from the store sees the new value.
function applyLike(store: Store, postId: string): Store {
  const post = store.posts[postId];
  if (!post || post.likedByMe) return store;
  return {
    ...store,
    posts: { ...store.posts, [postId]: { ...post, likedByMe: true, likeCount: post.likeCount + 1 } },
  };
}

The two ideas combine. A response cache keyed by request gives you fast repeats and background refresh; a normalized layer beneath it means that when the feed response and the profile response both contain post 42, there is a single record for it, and a like applied to that record shows in both lists. Without that layer, each response holds its own copy, and the copies disagree until each is refetched, invalidated, or patched by hand.

When to use it

Cache when the same read repeats within a short window: a search box that sees the same prefix again, a feed someone returns to from a detail view, a profile opened twice. A query cache keyed by arguments gives the second visit an instant screen and, with a stale-while-revalidate policy, refreshes it behind the scenes. Choose the freshness window from how fast the data moves: a few seconds for suggestions that rank live inventory, minutes for a profile, and a longer staleTime than the default when a refetch on each mount would waste requests.

Normalize when the same record appears on several screens and can change in place: the same post in the feed, in its own view and on its author's profile. The Redux guide lists the payoff: an update touches one place, there is no duplicated data to keep in step, and lookups by ID are direct instead of searching arrays. With Apollo Client the choice is also a fetch policy per query. cache-first, the default, answers from the cache and asks the server on a miss; cache-and-network shows the cached result and refreshes it; network-only skips the cached read but still writes the result into the cache.

When a tap should show before the server replies, the cache is where the optimistic write goes. TanStack Query's pattern: cancel any refetch in flight for that key so it can't overwrite your change, snapshot the current entry, write the hoped-for value, restore the snapshot if the mutation fails, and refetch the key once the mutation settles either way. A normalized store makes this one write instead of one per list that contains the post. The rollback details are in Optimistic updates and rollback.

When not to

Don't serve a cached answer when a stale one has a real cost: a balance before a transfer, seats left at checkout, a one-time code. Fetch at the moment of the decision and show a loading state; the time saved isn't worth a wrong number on screen. The same goes for a suggestion list whose results depend on something that changed and isn't part of the key, such as the person's location or a filter they just toggled; put it in the key or don't reuse the entry.

Don't normalize when nothing is edited in place. A list that is read, scrolled and discarded, with no like, edit or delete reflected elsewhere, gains little from being split into tables, and you pay for the mapping code in and out and for records that need a stable ID. A per-request cache that stores whole responses is usually enough there, and it's what TanStack Query and RTK Query give you with no extra setup.

Don't keep answers indefinitely. An autocomplete box that caches each new prefix someone types can grow with every keystroke, so give unused entries a short life: 60 seconds in RTK Query and 5 minutes in TanStack Query v5 unless you change them, and shorter still for suggestion results that lose value within a session.

Compared

ApproachWhat it keepsReach for it whenThe simpler option wins when

No cache

Nothing

A stale value is costly, or the read happens once

It is the simpler choice by default; it loses when repeats are frequent and latency shows

Per-request cache (TanStack Query, RTK Query)

Whole responses under a query key

Identical reads repeat; screens are revisited

Data must be current on each read, so there is nothing worth keeping

Stale-while-revalidate

Cached response plus a background refetch

An instant screen matters and a brief stale moment is acceptable

Two renders would confuse (a total that changes under the eye); fetch once instead

Normalized store (Apollo InMemoryCache, Redux entity tables)

One record per ID; lists of IDs

A record shows and changes on several screens

Nothing is edited in place, or records lack stable IDs; whole responses are enough

HTTP cache (Cache-Control)

Responses held by the HTTP layer, outside app code

Shared, rarely changing GET resources

You need to change a cached record from the app, which an HTTP cache can't see

In a picture

Feed responseSplit recordsPosts by IDFeed IDsFeed cardDetail view

Step 1 of 3

A response is split into records

The feed response arrives and is broken into records: each post and user goes into a map by ID, and the feed itself becomes a list of post IDs. The feed card and the detail view both read post 42 from the same map.

How to say it in an interview

The common mistake

Quiz

TanStack Query v5 with default settings: a component unmounts, and a component with the same key mounts 2 minutes later. What does it show?
The same post appears in the feed and on the author's profile, each loaded by its own query into a per-request cache. The person likes it from the feed. What does the profile show?
Someone types a word, deletes it, and types it again 3 seconds later. Your box answers from the cache. When is that the wrong call?
Two GraphQL responses each contain an object. When does Apollo Client's InMemoryCache store them as one record?

Questions that use this

Hear it in

Related

Sources

  1. TanStack Query v5: Important Defaults
  2. TanStack Query v5: Optimistic Updates
  3. Redux Toolkit, RTK Query: Cache Behavior
  4. Redux: Normalizing State Shape
  5. Apollo Client: Caching in Apollo Client (overview)
  6. Apollo Client: Queries (setting a fetch policy)
  7. RFC 5861: HTTP Cache-Control Extensions for Stale Content
  8. vercel/swr on GitHub: React Hooks for Data Fetching
Sign in to report a mistake