React cache()

Memoize expensive database queries across Server Components.

Next.js6 min readConcept 30 of 65

Extending Request Memoization

We learned earlier that Next.js automatically memoizes fetch() calls. If five components fetch() the same URL, only one network request is made.

But what if you aren't using fetch? What if you are querying a database directly using Prisma, Drizzle, or a MongoDB client? React's cache() function extends request memoization to ANY async function.

The Component Era Problem

In modern Next.js, the best practice is for components to fetch their own data rather than passing props down through a dozen layers (prop drilling).

But if Layout.tsx, Header.tsx, and Profile.tsx all need the current user's database record, querying the DB in all three places would be disastrous for performance. cache() solves this.

Wrapping Your Queries

You import cache from React (not Next.js). You wrap your data access function: const getUser = cache(async (id) => await db.user.find(id)).

Now, you can call getUser(1) in as many Server Components as you want. The first component triggers the database query; the subsequent components instantly receive the cached result from memory.

The ORM Avalanche

Watch the render cycle of a page that queries a database without fetch. Notice how the un-cached version batters the database with redundant queries, while the cache() version resolves the first query and serves the rest from memory.

DB Queries0

Next.js Server Render

Layout.tsxgetUser(1)
Header.tsxgetUser(1)
Profile.tsxgetUser(1)
React Request
Memory
PostgreSQL
External Network

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1When should you explicitly use React's `cache()` function?
  2. 2How long does data stored in React's `cache()` persist?

Remember this

  • Next.js only auto-memoizes fetch() calls.
  • Use React cache() to memoize direct database queries (Prisma, SQL, SDKs).
  • It prevents duplicate work when multiple Server Components request the same data.
  • cache() data only lives for the duration of a single HTTP request.
  • Failing to use cache() with ORMs can lead to severe database overload.

Done with this concept?

Mark it complete to track your progress. No login needed.