Next.js Discord

Discord Forum

Caching a server function doesn't work?

Answered
Transvaal lion posted this in #help-forum
Open in Discord
Transvaal lionOP
Am I fundamentally misunderstanding something here?

Code example and docs screenshot attached

My assumption of the minimal example in the screenshot should be that Next caches the fetchData call, and so refreshing the webpage should reuse that data (showing the time at which the function was cached). That doesn't happen, instead the fetchData function is called on every refresh and shows the current time.

Docs: https://nextjs.org/docs/app/building-your-application/data-fetching/caching#react-cache
Answered by joulev
dev mode? in prod mode it should be statically generated and the printed time is always the build time
View full answer

8 Replies

Answer
the reason it is called after each refresh in dev mode is because this cache() doesn't handle the cache that you're talking about

this cache() handles deduplication, so during a rendering, if it is called 10 times, it would be run only once. If you export this fetchData from a different file, then use it in both the root layout and in this page for example, it is only executed once during one rendering

cross-rendering caching is handled by static/dynamic rendering https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic-rendering. everything is dynamic in dev mode, hence that function is called at every refresh. pages are static by default in prod mode, so in prod mode that function should print the build time; if you explicitly opt to dynamic rendering then it will print the request time
Transvaal lionOP
@joulev thanks a lot, that answers my question and more. yeah dev mode was the culprit locally
Transvaal lionOP
@Transvaal lion CodeSnap :)
Japanese flying squid
Thanks brother any extension u would recommend i will search about but it increase my productivity thanks