Next.js Discord

Discord Forum

React cache() usage with MongoDB

Answered
Riday πŸ’™ posted this in #help-forum
Open in Discord
Hi,
How would you use react's cache function for maximum benefits?
I have certain functions all over my codebase that return a collection - getUserCollection(), getSessionCollection(), etc. Do I wrap these with the cache function?

They simply return the collection with types annotated:
export async function getUserCollection(db?: Db) {
    if (!db) db = await getDb();
    return db.collection<User>(COLLECTIONS.USERS);
}


What are the best practices for this kind of thing?
Answered by Ray
no issue as long as you are not using that function inside middleware
View full answer

15 Replies

@Riday πŸ’™ Hi, How would you use react's cache function for maximum benefits? I have certain functions all over my codebase that return a collection - `getUserCollection()`, `getSessionCollection()`, etc. Do I wrap these with the cache function? They simply return the collection with types annotated: ts export async function getUserCollection(db?: Db) { if (!db) db = await getDb(); return db.collection<User>(COLLECTIONS.USERS); } What are the best practices for this kind of thing?
cache() from react is useful when you are going to call that function in multiple place.
for example
export const getSession = cache(async () => [])

// layout.tsx
export default async function Layout({children}) {
  const session = await getSession()

  return (
    <>
      <Nav />
      {children}
    </>
  )
}

// page.tsx
export default async function Page() {
  const session = await getSession()
}

// nav.tsx
export default async function Nav() {
  const session = await getSession()
}
it will also be deduped at build time
Okay, so there won't be any weird issues if I wrap everything with cache()?
@Riday πŸ’™ Okay, so there won't be any weird issues if I wrap everything with cache()?
no issue as long as you are not using that function inside middleware
Answer
Okay
No, the pattern = using getSession in root layout
I am facing this issue where every single page in my app is dynamic... But, pages like about, terms, etc have literally nothing except static text
then it should be using dynamic function on the page
Nope
it is not related to cache()
Okay, I will create a new thread