Introduction
The cache()
function in React 19 is designed to improve performance in React Server Components by preventing unnecessary duplicate work.
What It Does
Remembers Results: It wraps around a function and remembers what that function returned for specific inputs.
Shares Data: When multiple components need the same data, they get the cached result instead of fetching it again.
How to Use It
import { cache } from "react";
// Create a memoized function outside components
const getUser = cache(async (userId) => {
return await db.getUser(userId);
});
// Use it in multiple components
function ProfileHeader({ userId }) {
const user = getUser(userId);
// ...
}
function ProfileStats({ userId }) {
const user = getUser(userId);
// ...
}
Important Rules
Server-Only: Only works in React Server Components, not client components.
Define Outside Components: Create memoized functions outside components and import them where needed.
Same References Matter: If you pass objects or arrays as arguments, they need to be the same reference to hit the cache.
Fresh Per Request: The cache resets with each new server request.
Preload Pattern: You can start fetching data early without awaiting, then await later when you need it:
function Page({ userId }) { // Start fetching but don't wait getUser(userId); return ( <> <OtherContent /> <Profile userId={userId} /> {/* Will use the already-started fetch */} </> ); }
Common Mistakes to Avoid
Creating the memoized function inside a component (creates a new cache each render)
Using different memoized functions for the same data (they don't share caches)
Calling memoized functions outside of components (won't use the cache)
- Memoized functions from
cache()
must be called inside React components to actually access the cache. If you call them outside of a component context, they'll still run the original function but won't look for cached results or store new results in the cache.
- Memoized functions from
Using complex objects as keys without ensuring same reference
Main Benefits
Stops Repeating Work: Components can share results, so they don't all do the same task.
Prevents Fetch Delays: Start getting data early in the component tree.
Keeps Components Independent: Components can get their own data without repeating tasks.