patternjavascriptTip
React cache() Function for Request-Scoped Deduplication
Viewed 0 times
react cacheserver componentsdeduplicationrequest scoped cachenext.js
Problem
Multiple React Server Components in the same render tree each call the same async function (e.g., getUser(id)) with the same arguments, causing redundant DB queries per request.
Solution
Wrap the function with React's cache() utility. It deduplicates calls with the same arguments within a single server render pass. Each new request gets a fresh cache — there is no cross-request pollution.
Why
React cache() is request-scoped, so it is safe to use for user-specific data. It eliminates the need to prop-drill data through the component tree just to avoid duplicate fetches.
Gotchas
- React cache() only works in React Server Components environments (React 18+ / Next.js App Router). It does not work in client components.
- The cache is cleared between requests — it is NOT a persistent cache. For persistent caching, use Redis or Next.js fetch cache.
- cache() requires the function to be defined at module scope (not inside a component) for the deduplication to work correctly.
Code Snippets
React cache() for deduplication
import { cache } from 'react';
import { db } from '@/lib/db';
export const getUser = cache(async (id) => {
return db.users.findById(id);
});
// Both components call getUser(123), but DB is queried only once per request
async function Header() { const user = await getUser(123); ... }
async function Sidebar() { const user = await getUser(123); ... }Revisions (0)
No revisions yet.