0 day streak
javascript / intermediate
Snippet

Request Memoization with React cache()

React cache allows you to memoize data fetches on a per-request basis. If multiple components in the same tree request the same data, the function only executes once, saving network resources.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
import { cache } from 'react';
import db from './lib/db';
export const getUser = cache(async (id: string) => {
const user = await db.user.findUnique({ where: { id } });
return user;
});
// Usage in multiple components during the same render cycle
const user = await getUser('123');
nextjs
Breakdown
1
export const getUser = cache(async (id: string) => {
Wraps the database call in cache() to ensure it only runs once per server request.
2
const user = await getUser('123');
Subsequent calls to this function with the same ID will return the cached result immediately.