Skip to main content

Server Cache React

Source: .agents/references/coding-standard/vercel-react-best-practices/rules/server-cache-react.md

Metadata

  • title: Per-Request Deduplication with React.cache()
  • impact: MEDIUM
  • impactDescription: deduplicates within request
  • tags: server, cache, react-cache, deduplication, app-router

Content

This repo: Pages Router only — React.cache() is for App Router / RSC request deduplication. Prefer Promise.all in getStaticProps / getServerSideProps, shared data helpers called once per request, or server-cache-lru for cross-request caching. Do not introduce React.cache() unless migrating to App Router.

Per-Request Deduplication with React.cache()

In App Router, React.cache() deduplicates async work within a single RSC request (auth, DB, etc.).

App Router usage (not used in this repo):

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 }
})
})

Pages Router alternative (this repo)

Deduplicate within one getServerSideProps / getStaticProps call by fetching once and passing results in props:

import type { GetServerSideProps } from 'next'

export const getServerSideProps: GetServerSideProps = async () => {
const user = await getCurrentUser()
const [posts, settings] = await Promise.all([
fetchPostsForUser(user.id),
fetchSettingsForUser(user.id)
])
return { props: { user, posts, settings } }
}

For repeated calls across separate data functions on the same page, extract a shared helper invoked once inside a single data function.

Reference: React.cache documentation