← Back
Edit Post
Title
Description
Request deduplication with cache(), combining with "use cache" directive.
Content
Markdown supported
# React cache() 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. ## The Pattern Wrap your data fetching functions with `cache()`: ```tsx 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: ```tsx // Both use the same cached result export async function generateMetadata({ params }) { const { slug } = await params; const post = await getPostBySlug(slug); return { title: post.title }; } export default async function PostPage({ params }) { const { slug } = await params; const post = await getPostBySlug(slug); return <article>{post.content}</article>; } ``` ## cache() vs "use cache" 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 | ## Combining Both Use them together for maximum efficiency: ```tsx export const getPublishedPostBySlug = cache(async (slug: string) => { 'use cache'; cacheTag(`post-${slug}`); const post = await prisma.post.findUnique({ where: { slug, published: true }, }); if (!post) notFound(); return post; }); ``` - `cache()` ensures multiple calls within a render share the same promise - `"use cache"` ensures the result is cached across requests - `cacheTag()` enables targeted invalidation ## When to Use cache() Wrap any data fetching function that might be called multiple times during a render: - Functions called by both `generateMetadata` and page components - Utility queries used across multiple Server Components - Any async function where arguments determine the result The function must return a promise, and React uses the arguments to determine cache keys.
Published
Save Changes
Cancel