javascript / intermediate
Snippet
Per-Request Data Memoization with React cache
React's cache function allows you to memoize data fetches within a single render pass. If multiple components request the same data during one request, the database is only queried once.
snippet.js
1
2
3
4
5
6
import { cache } from 'react';export const getItem = cache(async (id) => {const item = await db.item.findUnique({ where: { id } });return item;});
nextjs
Breakdown
1
cache(async (id) => { ... })
Wraps the fetcher function to ensure the result is reused for identical arguments in the same request.
2
export const getItem
Exposes the memoized function so it can be called from different Server Components.