Skip to content

React.cache()로 요청별 중복 제거

Overview

Use React.cache() for server-side request deduplication. Authentication and database queries benefit most.

Impact

  • Priority: MEDIUM
  • Performance: deduplicates within request

Usage

typescript
import { cache } from "react"

export const getCurrentUser = cache(async () => {
  const session = await auth()
  if (!session?.user?.id) return null
  return await db.user.findUnique({
    where: { id: session.user.id },
  })
})

Within a single request, multiple calls to getCurrentUser() execute the query only once.

How It Works

React.cache() is a caching mechanism provided by React Server Components that offers per-request memoization.

Common Scenario

typescript
// Called in Layout
async function Layout() {
  const user = await getCurrentUser() // 1st call
  return <div>...</div>
}

// Called in Page
async function Page() {
  const user = await getCurrentUser() // Returned from cache (no DB call)
  return <div>...</div>
}

// Called in another component
async function Sidebar() {
  const user = await getCurrentUser() // Returned from cache (no DB call)
  return <div>...</div>
}

All three components call getCurrentUser(), but the actual DB query executes only once.

Key Points

  • Request scope: Cache persists only within a single HTTP request
  • Auto clear: Re-executes on next request
  • Type safe: Full TypeScript support
  • Server only: Cannot be used in client components

Common Use Cases

  • Authentication functions (getCurrentUser, getSession, etc.)
  • Common database queries
  • Functions called from multiple components
  • Static configuration data

Cautions

  • Use LRU cache for cross-request caching needs
  • Use with proper permission checks for sensitive data
  • Cache works at function level (different args = separate cache)

Tags: server, cache, react-cache, deduplication