Next.js provides an experimental API called unstable_cache
. It caches non-fetch
requests in the data cache, which can be shared between users. It takes 3 parameters:
- The function you want to cache.
- The key for the cache.
- (Optional) Options for revalidation time or tags.
import { getGuides } from "./data"
import { cache as unstable_cache } from "next/cache"
const getCachedGuides = cache(city => getGuides(city), ["guides-cache-key"])
export default async function Page({ params }) {
const guides = await getCachedGuides(params.city)
// ...
}
In the example, we cache the getGuides
function in the data cache with the key ["guides-cache-key"]
. The second time you call getCachedGuides
, it will retrieve data from the data cache instead of calling getGuides
.
References