javascript / expert
Snippet
Request-Scoped Memoization for Server Components
React's `cache` function allows you to memoize data fetching or expensive computations within a single request lifecycle. This prevents redundant API calls or DB queries when multiple Server Components need the same data.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
import { cache } from 'react';import { db } from './database';export const getProjectMetrics = cache(async (projectId: string) => {console.log(`Fetching metrics for ${projectId}`);const metrics = await db.metrics.findUnique({ where: { projectId } });return metrics;});// Usage in multiple Server Components for the same request// Component A: const data = await getProjectMetrics('123');// Component B: const data = await getProjectMetrics('123'); // Uses cache
nextjs
Breakdown
1
export const getProjectMetrics = cache(async ...
Wraps an asynchronous function to store its result for the duration of a single user request.
2
console.log(...);
This log will only execute once per request, even if the function is called multiple times.
3
return metrics;
Returns the result directly from memory on subsequent calls within the same server render pass.