Next.js Discord

Discord Forum

Official use of unstable_cache?

Answered
Southern rough shrimp posted this in #help-forum
Open in Discord
Southern rough shrimpOP
Hi,

I'm looking at [these docs](https://nextjs.org/docs/app/api-reference/functions/unstable_cache#example), and I'm so confused how you actually utilise this function? In the bottom example:

import { unstable_cache } from 'next/cache'
 
export default async function Page({
  params,
}: {
  params: Promise<{ userId: string }>
}) {
  const { userId } = await params
  const getCachedUser = unstable_cache(
    async () => {
      return { id: userId }
    },
    [userId], // add the user ID to the cache key
    {
      tags: ['users'],
      revalidate: 60,
    }
  )
 
  //...
}


it utilises the userId outside the scope of the function. What if I define this cached function in a lib/mydatatype.ts? Then we don't have that outside userId from params
Answered by LuisLl
That’s fine if you add more keys👍

Side note, you might also want to add the id to your tags array here, to be able to granularly invalidate the cache for a specific user if you want, and not all users that are sharing the same tag.
View full answer

4 Replies

Southern rough shrimpOP
This is my current function, but it's based off guesswork:

export const getUserAliases = unstable_cache(
  async (userId: string, query: string) => {
    return db.query.aliases.findMany({ ... });
  },
  ["aliases"],
  {
    revalidate: 60,
    tags: ["user-aliases"],
  },
);
If you define your function outside of the scope of the component then it won’t be closing over any external variable, except for its own arguments.

unstable_cache automatically generates a unique key based on the function signature itself, this is the stringified version of the function and its parameters.

You only need to provide extra information in the keyParts array when your function is closing over an external variable that does not come through as an argument, otherwise it’s not required.

So in the hypothetical case where you pull that function outside the component now you’ll have to pass the params as an argument to the cache function, which will automatically add params to the keyParts array. Makes sense?
@Southern rough shrimp This is my current function, but it's based off guesswork: ts export const getUserAliases = unstable_cache( async (userId: string, query: string) => { return db.query.aliases.findMany({ ... }); }, ["aliases"], { revalidate: 60, tags: ["user-aliases"], }, );
That’s fine if you add more keys👍

Side note, you might also want to add the id to your tags array here, to be able to granularly invalidate the cache for a specific user if you want, and not all users that are sharing the same tag.
Answer
Southern rough shrimpOP
Thanks for your help