Rendering

React cache in Server Components

React cache memoizes a function within the Server Component request context. Create the wrapper once at module scope; separately wrapped functions do not share results. Object arguments are identity-sensitive. Rejected computations may be reused. It is not a cross-request data store. Source: https://react.dev/reference/react/cache. Documentation-reviewed illustrative draft; installed declarations and runtime not verified.

Formal Syntax & Structure

nextjs syntaxnextjs
import { cache } from "react"; const memoized = cache(fn);

Working Example

Example Snippetnextjs
import "server-only";import { cache } from "react";import { readPublishedBook } from "./repository";export const getPublicBook = cache(async (slug: string) => {  if (!/^[a-z0-9-]{1,60}$/.test(slug)) return null;  const row = await readPublishedBook(slug);  return row ? { slug: row.slug, title: row.title } : null;});
Next.js Reference