Capítulo 74 de 116

Chapter 74: cache

Core Idea

cache(fn) memoizes a function's result per server request (in a React Server Components context) — calling the cached function multiple times with the same arguments during one render pass reuses the first call's result instead of redoing the work.

Key Concepts

  • Server-only, RSC-specific: cache is part of the react package's server-rendering surface, meant for use inside Server Components — it's not a general client-side memoization utility (that's useMemo, Ch 59, which is per-component-instance rather than per-request).
  • Request-scoped, not persistent: the cache lives only for the duration of a single server render/request — it doesn't persist data across separate requests or act as a general application-level cache.
  • Deduplicates repeated calls with identical arguments within that one render — useful when multiple components independently need the same derived/fetched data (e.g. several components each calling getUser(id)), avoiding redundant work without requiring the components to coordinate directly.
  • Arguments determine cache key: calls with different arguments are cached separately; the function must be safe to memoize by argument identity/equality the way any cache key works.

Code Examples

const getUser = cache(async (id) => {
  return db.users.findById(id);
});

// Two different Server Components calling getUser(42) during the same
// request share one actual database call.
  • What it demonstrates: two independent call sites requesting the same data during one server render, deduplicated automatically instead of hitting the database twice.

Key Takeaways

  1. Scope your mental model to "per server request," not "per component" (that's useMemo) or "persistent" (that's an external cache/store).
  2. Reach for it specifically to deduplicate redundant data-fetching calls across independent Server Components rendering the same request.
  3. It's part of the RSC toolkit — not applicable inside Client Components.

Connects To

  • Ch 110 (Server Components): the rendering context this function is meant for.
  • Ch 59 (useMemo): the client-side, per-component-instance analog for a different scope of caching.