#cached number in layout component

1 messages · Page 1 of 1 (latest)

tender bladeBOT
#

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

#

To display a cached number from the database in a layout component for multiple pages without refetching it on each navigation, you can use the React cache function in Next.js. This approach allows you to memoize the data fetch, ensuring it's only executed once across multiple renders. Here's how you can implement this:

  1. First, create a utility function to fetch the number from your database and wrap it with the React cache function:
import { cache } from 'react'
import db from '@/lib/db'

export const getCachedNumber = cache(async () => {
  const number = await db.getNumber() // Replace with your actual database query
  return number
})
  1. Then, in your layout component, use this cached function:
import { getCachedNumber } from '@/utils/get-cached-number'

export default async function Layout({ children }) {
  const cachedNumber = await getCachedNumber()

  return (
    <div>
      <header>Cached Number: {cachedNumber}</header>
      {children}
    </div>
  )
}

This approach leverages the React cache function, which is designed to memoize the return value of a function, allowing you to call it multiple times while only executing it once React cache function (https://nextjs.org/docs/app/building-your-application/caching#react-cache-function). This is particularly useful for database queries or other data fetching operations that don't use the fetch API directly.

By implementing this method, the number will be fetched once when the layout is first rendered, and then reused across multiple page navigations without refetching. This approach is efficient and helps maintain consistent data across your application's pages.

#

Remember that this caching is per-request, so if you need the data to persist across multiple requests or want to implement time-based revalidation, you might need to consider additional caching strategies or use Next.js's data caching features.

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

#

@west talon Kapa.ai is still learning and improving, please let me know how I did by reacting below.