Careeroza
The use cache Directive
Cache Components
Next.js 16 adds Cache Components: you mark a function or component with 'use cache' and Next.js caches its result. It works for any async code (database, ORM), not just fetch. Enable it in the config:
next.config.ts
next.config.ts
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
cacheComponents: true, // Next.js 16 (in 15 this was experimental.useCache / dynamicIO)
};
export default nextConfig;Usage
import { cacheLife, cacheTag } from 'next/cache';
import { prisma } from '@/lib/prisma';
export async function getCategoryProducts(slug: string) {
'use cache';
cacheLife('hours'); // built-in profiles: 'seconds', 'minutes', 'hours', 'days', 'weeks', 'max'
cacheTag('category-' + slug);
return prisma.product.findMany({ where: { category: { slug } } });
}- The arguments (
slug) become part of the cache key. - Inside a cached function you cannot call
cookies()orheaders(); read them outside and pass values in. - This is the direction Next.js is moving;
unstable_cacheand route-levelrevalidatestill work.