Request deduplication with cache(), combining with "use cache" directive.
Duplicate requests extend loading time unnecessarily. When multiple components need the same data—say, the page component and a metadata function both reading a post—you don't want two database queries.
React's cache() deduplicates requests within a single render pass. Multiple calls with the same arguments return the same promise.
Wrap your data fetching functions with cache():
import { cache } from 'react';
import { notFound } from 'next/navigation';
export const getPostBySlug = cache(async (slug: string) => {
const post = await prisma.post.findUnique({
where: { slug },
});
if (!post) {
notFound();
}
return post;
});Now multiple components can call getPostBySlug(slug)—only one database query executes:
// Both use the same cached result
export async function generateMetadata({ params }) {
const { slug } = await params;
const post = await getPostBySlug(slug);
These serve different purposes:
| Feature | cache() | "use cache" |
|---|---|---|
| Scope | Single render pass | Across requests |
| Purpose | Deduplicate concurrent calls | Pre-render/cache results |
| Import | react | Directive |
Use them together for maximum efficiency:
export const getPublishedPostBySlug = cache(async (slug: string) => {
'use cache';
cacheTag(`post-${slug}`);
const
cache() ensures multiple calls within a render share the same promise"use cache" ensures the result is cached across requestscacheTag() enables targeted invalidationWrap any data fetching function that might be called multiple times during a render:
generateMetadata and page componentsThe function must return a promise, and React uses the arguments to determine cache keys.