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.
| Concern | cache | useMemo |
|---|---|---|
| Primary environment | Server Components | Component rendering |
| Sharing scope | Can share memoized work across Server Components in a request | Belongs to a component instance/render lifecycle |
| Good for data fetches | Yes | No; useMemo is for pure calculations |
| Invalidation model | React invalidates server cache across requests | Recomputes 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>;
}