2026-01-20 16:19:16 +08:00
---
title: Per-Request Deduplication with React.cache()
impact: MEDIUM
impactDescription: deduplicates within request
tags: server, cache, react-cache, deduplication
---
## Per-Request Deduplication with React.cache()
Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.
**Usage: **
``` typescript
2026-02-05 21:40:43 +08:00
import { cache } from 'react' ;
2026-01-20 16:19:16 +08:00
export const getCurrentUser = cache ( async ( ) = > {
2026-02-05 21:40:43 +08:00
const session = await auth ( ) ;
if ( ! session ? . user ? . id ) return null ;
2026-01-20 16:19:16 +08:00
return await db . user . findUnique ( {
2026-02-05 21:40:43 +08:00
where : { id : session.user.id } ,
} ) ;
} ) ;
2026-01-20 16:19:16 +08:00
```
Within a single request, multiple calls to `getCurrentUser()` execute the query only once.
**Avoid inline objects as arguments: **
`React.cache()` uses shallow equality (`Object.is` ) to determine cache hits. Inline objects create new references each call, preventing cache hits.
**Incorrect (always cache miss): **
``` typescript
const getUser = cache ( async ( params : { uid : number } ) = > {
2026-02-05 21:40:43 +08:00
return await db . user . findUnique ( { where : { id : params.uid } } ) ;
} ) ;
2026-01-20 16:19:16 +08:00
// Each call creates new object, never hits cache
2026-02-05 21:40:43 +08:00
getUser ( { uid : 1 } ) ;
getUser ( { uid : 1 } ) ; // Cache miss, runs query again
2026-01-20 16:19:16 +08:00
```
**Correct (cache hit): **
``` typescript
const getUser = cache ( async ( uid : number ) = > {
2026-02-05 21:40:43 +08:00
return await db . user . findUnique ( { where : { id : uid } } ) ;
} ) ;
2026-01-20 16:19:16 +08:00
// Primitive args use value equality
2026-02-05 21:40:43 +08:00
getUser ( 1 ) ;
getUser ( 1 ) ; // Cache hit, returns cached result
2026-01-20 16:19:16 +08:00
```
If you must pass objects, pass the same reference:
``` typescript
2026-02-05 21:40:43 +08:00
const params = { uid : 1 } ;
getUser ( params ) ; // Query runs
getUser ( params ) ; // Cache hit (same reference)
2026-01-20 16:19:16 +08:00
```
**Next.js-Specific Note: **
In 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:
- Database queries (Prisma, Drizzle, etc.)
- Heavy computations
- Authentication checks
- File system operations
- Any non-fetch async work
Use `React.cache()` to deduplicate these operations across your component tree.
Reference: [React.cache documentation ](https://react.dev/reference/react/cache )