Lesson 12 / 25

Caching Models: Cache Components and the Previous Model

Two ways Next.js caches work.

"use cache" and cacheLife

Recent Next.js versions offer Cache Components, enabled with cacheComponents: true in next.config.ts. With it, you mark functions, components or pages with the "use cache" directive and set a lifetime with cacheLife("hours") and similar profiles; arguments become part of the cache key, and cached parts form the static shell of a page while uncached parts stream in. Projects not using Cache Components use the previous model: fetch options such as next: { revalidate: 3600 }, unstable_cache for non-fetch functions, and route segment options like export const revalidate. The demo app in this course uses the previous (default) model. Next.js changes quickly between major versions; check the docs for your version (they ship inside node_modules/next/dist/docs).

Cached data with Cache Components (from the docs)

Shape of the API as shown in the Next.js 16 documentation; not part of the built demo.

// next.config.ts
const nextConfig = { cacheComponents: true };
export default nextConfig;

// app/lib/data.ts
import { cacheLife } from "next/cache";

export async function getProducts() {
  "use cache";
  cacheLife("hours");                 // how long the result stays fresh
  return db.query("SELECT * FROM products");
}

Pick one model per project

Read the caching guide for your version and use one model consistently; mixing advice from different versions is a common source of confusion.

Quick check: In the Cache Components model, how do you mark a function's result as cacheable?

  • Name the file cache.ts
  • Add the "use cache" directive and set a cacheLife
  • Use useMemo
  • Add a CSS class
Answer

Add the "use cache" directive and set a cacheLife — Directive plus lifetime.