Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply 62 React and Next.js performance optimization rules from Vercel Engineering
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
rules/server-cache-react.md
1---2title: Per-Request Deduplication with React.cache()3impact: MEDIUM4impactDescription: deduplicates within request5tags: server, cache, react-cache, deduplication6---78## Per-Request Deduplication with React.cache()910Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.1112**Usage:**1314```typescript15import { cache } from 'react'1617export const getCurrentUser = cache(async () => {18const session = await auth()19if (!session?.user?.id) return null20return await db.user.findUnique({21where: { id: session.user.id }22})23})24```2526Within a single request, multiple calls to `getCurrentUser()` execute the query only once.2728**Avoid inline objects as arguments:**2930`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.3132**Incorrect (always cache miss):**3334```typescript35const getUser = cache(async (params: { uid: number }) => {36return await db.user.findUnique({ where: { id: params.uid } })37})3839// Each call creates new object, never hits cache40getUser({ uid: 1 })41getUser({ uid: 1 }) // Cache miss, runs query again42```4344**Correct (cache hit):**4546```typescript47const getUser = cache(async (uid: number) => {48return await db.user.findUnique({ where: { id: uid } })49})5051// Primitive args use value equality52getUser(1)53getUser(1) // Cache hit, returns cached result54```5556If you must pass objects, pass the same reference:5758```typescript59const params = { uid: 1 }60getUser(params) // Query runs61getUser(params) // Cache hit (same reference)62```6364**Next.js-Specific Note:**6566In 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:6768- Database queries (Prisma, Drizzle, etc.)69- Heavy computations70- Authentication checks71- File system operations72- Any non-fetch async work7374Use `React.cache()` to deduplicate these operations across your component tree.7576Reference: [React.cache documentation](https://react.dev/reference/react/cache)77