Frontend Case Studies

Topic F8

Server state caching

Keeping server data in a per-key cache: no duplicate fetches, no repeat spinners.

9 min · intermediate

Watch: when you go back to a page you just visited, the saved data shows at once, with no loading spinner.

pagesAPIHomeProduct 1HomeProduct 1
  • moving now
  • being checked
  • no longer used
Step 1 of 6

Every component calls fetch itself in a useEffect when it mounts, and keeps the result in its own local state.

Server data is a copy of something the server owns. A per-key cache lets it be shared and shown instantly.

The trouble with fetch in useEffect

  • Two components needing the same data send two identical requests.
  • Going back to a page you just visited means another spinner.
  • After you change data (say renaming something), other components showing it don't know and keep the old value.
  • You handle loading, errors, retries, cancelling on unmount, and out-of-order replies all by yourself.
Code, for programmersTanStack Query
function useUser() {
  return useQuery({
    queryKey: ["user"],                  // the cache key
    queryFn: () => fetch("/api/me").then((r) => r.json()),
    staleTime: 60_000,                   // fresh for 1 minute: no refetch at all
  });
}

// header and page both call useUser(): one request, one cache entry
const { data: user, isPending } = useUser();

// after a change, tell the cache which keys are now out of date
const rename = useMutation({
  mutationFn: (name) => fetch("/api/me", { method: "PATCH", body: JSON.stringify({ name }) }),
  onSuccess: () => queryClient.invalidateQueries({ queryKey: ["user"] }),
});

Stale-while-revalidate

The core pattern: show the old data from the cache now, then fetch the latest in the background and quietly swap it in if it differs. Users never see a spinner for data they've seen before, and still get fresh data within milliseconds. It's the same idea as the HTTP header Cache-Control: stale-while-revalidate and backend caching (Caching and LRU caches (B4) and Cache invalidation, TTL and stampedes (B5)), including the hardest problem: deciding when data is stale.

Quiz

  1. The header and the page both call useQuery(['user']) at the same time. How many requests?

  2. What does stale-while-revalidate mean?

  3. After renaming through a mutation, why call invalidateQueries(['user'])?

0 of 3 answered.