React cache()
Memoize expensive database queries across Server Components.
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.
Next.js Server Render
Memory
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
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.