Next.js Discord

Discord Forum

Issue with cache in APPDIR

Answered
Barbary Lion posted this in #help-forum
Open in Discord
Avatar
Barbary LionOP
Hello everyone, I am facing an issue with caching responses from SDK. It is not using default fetch, it's using GQL client (with some provider).
So I found in docs that I should use 'cache' function from react, so I created file inside /app/utils/getCategories.ts with following code:
import { siteConfig } from '@/constants';
import { sdk } from '@/lib/sdk';
import { cache } from 'react';

export const revalidate = 3600;

export const getCategories = cache(async () => {
const {
use: { categories },
} = await sdk.getCatalogCategories();
return categories;
});
(response has around 2MB, if that matters)

This function is being fired inside /app/pl/page.tsx , but the response is still not cached, so everytime I refresh the page / go from navigation this function strikes to SDK.
Any ideas ?
Answered by fuma & joulev pray for Schneider
The cache function from React is for "Memorization" (aka dedup), it only lives during component render.

If you want to cache the response with Next.js's Data Cache, for now, there's no recommended way to do this.

Some workarounds:
- Cache the page itself with revalidate or statically render the page
- Use unstable_cache from next/cache, it's not yet documented
View full answer

4 Replies

Avatar
Barbary LionOP
bump
Avatar
fuma & joulev pray for Schneider
The cache function from React is for "Memorization" (aka dedup), it only lives during component render.

If you want to cache the response with Next.js's Data Cache, for now, there's no recommended way to do this.

Some workarounds:
- Cache the page itself with revalidate or statically render the page
- Use unstable_cache from next/cache, it's not yet documented
Answer
Avatar
fuma & joulev pray for Schneider
Be careful that the caching behaviour is different between dev mode and production mode, you should only test it in production mode (next build && next start)
In your case, it actually works in production mode