Next.js Discord

Discord Forum

Caching function output with use cache with an object as a parameter?

Answered
Iridescent shark posted this in #help-forum
Open in Discord
Iridescent sharkOP
Just wondering if you can use an object as a parameter (just like when used with components) when using "use cache" with functions? I wasn't able to find an answer here: https://nextjs.org/docs/app/api-reference/directives/use-cache#caching-function-output-with-use-cache

If not then I suppose you must use parameters as primitive values like you do with React.cache?
Answered by luis_llanes
You mean if “use cache” automatic dependencies detection works for objects and complex types when received as parameters ?

Yes, the “use cache” will handle the serialization of different types of stuff like promises, complex objects, etc (everything React serialization supports), and what can’t be serialized will be replaced with a placeholder pointing to the actual value.

function example( {user, options, is working} ){
“use cache”

//user.name
//user.age

//options.whatever

// isWorking
}
View full answer

5 Replies

You mean if “use cache” automatic dependencies detection works for objects and complex types when received as parameters ?

Yes, the “use cache” will handle the serialization of different types of stuff like promises, complex objects, etc (everything React serialization supports), and what can’t be serialized will be replaced with a placeholder pointing to the actual value.

function example( {user, options, is working} ){
“use cache”

//user.name
//user.age

//options.whatever

// isWorking
}
Answer
Iridescent sharkOP
Yeah, that's awesome if that's the case.

Yeah I've actually read the article, I just looked for confirmation that it also worked for non-component functions as the examples usually show destructed props from components (which I guess are functions as well so yeah..)
Yea it’s powerful.

Anyway all could change that’s why it’s still experimental so have that in mind, hope they finally crack the caching mechanism and finally one with a nice DX and fair heuristics
Iridescent sharkOP
Yeah agree. Honestly, just rolling with Next feels like an experiment 😄 I do like the idea of "use cache" and it's very practical with all the detectable checks during dev to ensure "use cache", dynamic IO and partial prerendering works. But I also believe a lot of people are going to be upset with how much there is to think about when developing a Next solution with the new features