Nextjs Fundamentals · Caching & Revalidation

Cache Components

use cache

Cache Components

Cache Components is Next.js 16's explicit caching model. Caching is opt-in: by default every page, layout, and function runs at request time, and you mark the parts you want cached with the 'use cache' directive.

Enable the feature in next.config.ts:

const nextConfig = { cacheComponents: true };

export default nextConfig;

Then add 'use cache' at the top of a function or component body. Cached functions and components must be async:

import { cacheLife } from 'next/cache';

export async function getUsers() {
  'use cache';
  cacheLife('hours');
  return db.query('SELECT * FROM users');
}

You can cache at the data level (a function that fetches or computes) or the UI level (a whole component, page, or layout). Placing the directive at the top of a file caches every export in it. Next.js generates a cache key from the build ID, the function's identity, and its serializable arguments, so different inputs get separate entries. A cached scope cannot read runtime APIs like cookies() or headers() — read those outside and pass the values in as arguments.

You are about to answer a short quiz on use cache.

  1. Cache Components make caching opt-in: code runs at request time unless it is marked with 'use cache'.
  2. A function marked with 'use cache' must be async.
  3. To enable Cache Components in Next.js 16, set ___ : true in next.config.
  4. A cached function can read cookies() and headers() directly inside its 'use cache' scope.
  5. 'use cache' can cache a page, a component, or a ___.
  6. Different serializable arguments produce different cache entries for the same cached function.