#React cache

1 messages · Page 1 of 1 (latest)

last vigil
#

If I cache my db request function (getUserFromId) using the built in react cache, will that mean only 1 request to the db will be made if I fetch from layout and page on the same req?

feral smeltBOT
#

Hi @last vigil. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, if you use the React cache function to memoize your getUserFromId function, it will ensure that the function is only executed once, even if it's called multiple times within the same request. This means that only one query will be made to the database, even if you fetch data from both the layout and the page.

Here's an example of how you might use the cache function to memoize your getUserFromId function:

import { cache } from 'react'
import db from '@/lib/db'
 
export const getUserFromId = cache(async (id: string) => {
  const user = await db.user.findUnique({ id })
  return user
})

Then, in your layout and page, you can call getUserFromId like this:

import { getUserFromId } from '@/utils/get-user-from-id'
 
export default async function Layout({
  params: { id },
}: {
  params: { id: string }
}) {
  const user = await getUserFromId(id)
  // ...
}
import { getUserFromId } from '@/utils/get-user-from-id'
 
export default async function Page({
  params: { id },
}: {
  params: { id: string }
}) {
  const user = await getUserFromId(id)
  // ...
}

This will ensure that the getUserFromId function is only executed once, and the result is reused in both the layout and the page, reducing the number of database queries.

Sources:


Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@last vigil kapa.ai is still learning and improving, please let us know how it did by reacting below

last vigil
#

But if I make another request entirely, 1 more db query will be made @feral smelt

feral smeltBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Yes, that's correct. The React cache function only deduplicates requests within the same render pass. If you make another request entirely, such as in response to a user action or in a different page load, a new database query will be made.

This is because the purpose of the cache function is to prevent unnecessary duplicate requests during the same render pass, not to cache data across multiple requests or over time. If you need to cache data across multiple requests or over time, you might need to use a different caching strategy or tool.

Source: Next.js Docs: Data Cache (https://nextjs.org/docs/app/building-your-application/caching#data-cache)

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: