AceDevHub
Advanced React Interview QuestionsAdvancedComparison

React · Question 95

What does React cache do in Server Components, and how is it different from useMemo?

Direct answer

React cache memoizes a function's result for use during Server Component rendering so work can be shared across components in a server request, while useMemo caches one component's calculation between client renders based on dependencies.

ConcerncacheuseMemo
Primary environmentServer ComponentsComponent rendering
Sharing scopeCan share memoized work across Server Components in a requestBelongs to a component instance/render lifecycle
Good for data fetchesYesNo; useMemo is for pure calculations
Invalidation modelReact invalidates server cache across requestsRecomputes when dependencies change
profile.jsx
import { cache } from "react";

const getUser = cache(async (id) => {
  return db.user.find(id);
});

async function Avatar({ userId }) {
  const user = await getUser(userId);
  return <img src={user.avatarUrl} alt="" />;
}

async function ProfileName({ userId }) {
  const user = await getUser(userId);
  return <h1>{user.name}</h1>;
}