xonecas.io
556
Bn

bees-nest / files

bees-nest / .opencode / skills / vercel-react-best-practices / rules / server-cache-react.md

2.2 KB
1---
2title: Per-Request Deduplication with React.cache()
3impact: MEDIUM
4impactDescription: deduplicates within request
5tags: server, cache, react-cache, deduplication
6---
7
8## Per-Request Deduplication with React.cache()
9
10Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.
11
12**Usage:**
13
14```typescript
15import { cache } from 'react'
16
17export const getCurrentUser = cache(async () => {
18  const session = await auth()
19  if (!session?.user?.id) return null
20  return await db.user.findUnique({
21    where: { id: session.user.id }
22  })
23})
24```
25
26Within a single request, multiple calls to `getCurrentUser()` execute the query only once.
27
28**Avoid inline objects as arguments:**
29
30`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.
31
32**Incorrect (always cache miss):**
33
34```typescript
35const getUser = cache(async (params: { uid: number }) => {
36  return await db.user.findUnique({ where: { id: params.uid } })
37})
38
39// Each call creates new object, never hits cache
40getUser({ uid: 1 })
41getUser({ uid: 1 })  // Cache miss, runs query again
42```
43
44**Correct (cache hit):**
45
46```typescript
47const getUser = cache(async (uid: number) => {
48  return await db.user.findUnique({ where: { id: uid } })
49})
50
51// Primitive args use value equality
52getUser(1)
53getUser(1)  // Cache hit, returns cached result
54```
55
56If you must pass objects, pass the same reference:
57
58```typescript
59const params = { uid: 1 }
60getUser(params)  // Query runs
61getUser(params)  // Cache hit (same reference)
62```
63
64**Next.js-Specific Note:**
65
66In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks:
67
68- Database queries (Prisma, Drizzle, etc.)
69- Heavy computations
70- Authentication checks
71- File system operations
72- Any non-fetch async work
73
74Use `React.cache()` to deduplicate these operations across your component tree.
75
76Reference: [React.cache documentation](https://react.dev/reference/react/cache)