Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 72 Β· Data Fetching and Caching

The use cache Directive and Cache Components

Learn the use cache directive in Next.js 16: caching functions and components, cache keys, cacheLife and cacheTag, and static shells with dynamic holes.

In the classic caching model, you control caching with options spread across your code: a cache option on one fetch, a revalidate number on another, a route setting at the top of a file. To understand what a page does, you must read all of them and remember the defaults. Cache Components, introduced in Next.js 16, takes a different approach. Rendering is dynamic by default, and you cache something by writing the directive "use cache" right where it is defined, the same way "use client" and "use server" work.

This lesson teaches the directive, how Next.js builds a cache key, how long entries live with cacheLife, how cacheTag names them, why request data like cookies cannot be read inside a cached scope, and how a page becomes a static shell with dynamic holes. Read Caching in Next.js: the Big Picture first if you have not yet, because this lesson assumes you know what the data cache and the full route cache do.

Real Next.js cannot run on this site, so its code is read-only. The two runnable examples are Node.js stand-ins: one models cache keys and lifetimes with a virtual clock, the other models a static shell with dynamic holes.

Turning it on

Cache Components is opt-in. You enable it in the config file, and from then on the rules in this lesson apply to the whole app:

TypeScript
// next.config.ts  (real Next.js 16, read-only)
import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
  cacheComponents: true,
};

export default nextConfig;

With the setting on, a component that touches uncached data or request data is rendered for each request, and something you mark with "use cache" is computed once and reused. Older route options such as dynamic and revalidate are replaced by the directive and its helper functions in this mode.

Marking things as cached

You can put the directive in three places. At the top of a file, it caches every exported async function or component in that file. Inside a function, it caches that function. Inside an async Server Component, it caches the component's rendered output.

TSX
// app/lib/posts.ts  (real Next.js, read-only)
import { cacheLife, cacheTag } from 'next/cache';

export async function getPost(id: string) {
  'use cache';
  cacheLife('hours');
  cacheTag('posts', `post-${id}`);

  const response = await fetch(`https://api.example.com/posts/${id}`);
  return response.json();
}
TSX
// app/blog/[id]/page.tsx  (real Next.js, read-only)
import { getPost } from '@/app/lib/posts';

export default async function Page({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const post = await getPost(id); // cached for an hour, per id

  return (
    <article>
      <h1>{post.title}</h1>
      <p>{post.summary}</p>
    </article>
  );
}

The directive must be the first statement in the function (before any other code, after only comments). A cached function has to be async, because the framework may need to wait for a stored result.

How the cache key is built

Two calls share a cache entry only if they are "the same call". Next.js builds the key from several things:

  • The function itself, identified by where it is defined.
  • Its arguments. getPost('1') and getPost('2') are different entries.
  • The values it closes over, such as a variable from an outer scope that the function uses.

Arguments and closed-over values must be serializable, with the same rules you learned for props in Inside the RSC Payload: plain data, not class instances or ordinary callbacks. There is one useful exception. A cached component may receive JSX as children or another prop without looking inside it. It just passes it through, so the cache does not need to know what it is.

How long entries live: cacheLife

cacheLife sets the lifetime of the entry. You can pass the name of a profile such as 'seconds', 'minutes', 'hours', 'days', 'weeks' or 'max', or pass an object. If you do not call it, a default profile applies. A profile has three numbers, and it helps to know what each one controls:

Setting Meaning
stale How long the browser may reuse the result without asking the server again.
revalidate After this many seconds the entry is old: the next request still gets it instantly, but the server refreshes it in the background.
expire After this many seconds with no refresh, the entry is too old to use. The next request must wait for a fresh value.
TSX
// real Next.js, read-only
import { cacheLife } from 'next/cache';

export async function getPrices() {
  'use cache';
  cacheLife({
    stale: 30,        // browser may reuse for 30 s
    revalidate: 300,  // refresh in the background after 5 minutes
    expire: 3600,     // never serve anything older than 1 hour
  });
  // ...
}

You can also define your own named profiles once in next.config.ts and use them everywhere, so a whole team agrees on what 'editorial' means. The named profiles that ship with Next.js have fixed numbers, which are listed in the official reference and may change between versions, so treat the name as a scale (seconds, minutes, hours...) and look the numbers up when they matter.

The behavior between revalidate and expire is the stale-while-revalidate pattern you saw with SWR in Fetching Data on the Client: visitors never wait for the refresh, they just see slightly older content for one more request.

A model of keys and lifetimes

The stand-in below implements the idea with a virtual clock, so every run is the same. useCache() wraps an async function. The key is the function's name plus the JSON of its arguments. A fresh entry is a HIT. An entry between revalidate and expire is STALE: the old value is returned and a refresh is started. An entry past expire is EXPIRED and the caller waits for a new run. The wrapped function counts how many times it really ran, so you can see what the cache saved.

Real Next.js stores entries differently and works across processes, but the key idea, arguments in the key and three ages, is the same. The lifetime here is revalidate: 60, expire: 3600 seconds.

Node.js Cache keys and lifetimes with a virtual clock

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at the log. The second call is a hit. Asking for post 2 is a separate key, so it is a miss. At 90 seconds, post 1 is older than the 60-second revalidate, so the caller is not kept waiting: it receives run 1 and the background refresh produces run 3. At 95 seconds the new value is a hit. Only after the 3,600-second expire does a caller have to wait again. Six calls cost four real runs.

Tags: names for groups of entries

cacheTag attaches one or more labels to an entry. A label by itself changes nothing. Its value comes later, when a mutation says "everything tagged posts is outdated now", which you will do in Revalidating Data. It is good practice to give each entry a broad tag (posts) and a specific one (post-42), so you can invalidate a single item or the whole list.

Request data cannot be read inside a cache

A cached scope must produce the same result for everyone who passes the same arguments. Cookies, headers and the current URL's search parameters differ per visitor, so reading them inside "use cache" is an error. The fix is to read them outside and pass what you need in as arguments, which also puts it into the cache key:

TSX
// real Next.js, read-only
import { cookies } from 'next/headers';
import { cacheLife } from 'next/cache';

async function getRecommendations(country: string) {
  'use cache';
  cacheLife('hours');
  return fetchRecommendations(country); // same answer for everyone in that country
}

export default async function Page() {
  const country = (await cookies()).get('country')?.value ?? 'us';
  const items = await getRecommendations(country); // one entry per country
  return <List items={items} />;
}

Notice that the cache is shared by many users, but the number of entries stays small, because the key is a country and not a user id. Pick cache keys with a limited number of values. Caching per user id works, but it fills the cache with entries that are rarely reused. Next.js also offers variants of the directive for other storage and per-user cases ("use cache: remote" and "use cache: private"), which are described in its reference.

Values computed inside a cached function are frozen until it is refreshed. A Date.now() or Math.random() there is evaluated once, and everyone gets that same value. That is correct for a cached price, but a bug for a "current time" label.

A static shell with dynamic holes

With Cache Components, Next.js tries to prerender each page at build time. Everything it can finish without request data goes into a static shell: plain markup, plus the output of any "use cache" scope. Parts that need request data or uncached live data cannot be finished, so they must sit inside a <Suspense> boundary. The shell contains the fallback in that place, and the real content streams in at request time. The shell is served instantly from the edge, and the holes are filled while the user is already looking at the page.

Three kinds of content

Static Needs nothing from the request. Part of the shell.
Cached Marked use cache. Also in the shell.
Dynamic Needs cookies or live data. Streams in.

Dynamic parts must wait inside Suspense.

1 / 2

If a dynamic part is not inside a <Suspense> boundary, Next.js stops with an error during the build or in development, because it could not produce any shell for that page. This is a feature: it forces you to decide what the visitor sees while data loads. The idea is developed in Partial Prerendering.

TSX
// app/page.tsx  (real Next.js, read-only)
import { Suspense } from 'react';

export default function Page() {
  return (
    <>
      <Header />                         {/* static */}
      <FeaturedProducts />               {/* "use cache": part of the shell */}
      <Suspense fallback={<CartSkeleton />}>
        <CartCount />                    {/* reads cookies: streams in */}
      </Suspense>
    </>
  );
}

The second stand-in builds the shell. A page is a list of parts, each static, cached or dynamic. A dynamic part with a fallback becomes a hole in the shell. A dynamic part without a fallback throws, like the real framework. Run it to see the shell, the final page and the failure.

Node.js Building a static shell with holes

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The shell holds the header and the product list as ready markup, and CartCount appears as its fallback marked with a hole comment. After streaming, only that span changes. The last run shows the rule: with no fallback, no shell can be built and the build fails.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. Where must the "use cache" directive be placed inside a function?

    Like other directives, it must come first in the function body. It can also go at the top of a file to cover all exports.
  2. 2. getPost('1') and getPost('2') are both cached functions. How many cache entries exist after calling both?

    The key includes the function and its serializable arguments, so each id gets its own entry.
  3. 3. An entry is older than revalidate but younger than expire. What does the next request get?

    That is stale-while-revalidate. The visitor is never kept waiting for the refresh. Only past expire must the request wait for a new value.
  4. 4. Why can't a cached function call cookies() directly?

    Read the cookie outside, then pass the value as an argument. That makes it part of the cache key, so each distinct value gets its own entry.
  5. 5. With Cache Components on, a dynamic component is not wrapped in Suspense. What happens?

    Dynamic content needs a Suspense boundary so that the shell has something to show. Without one Next.js raises an error, so you choose the loading state.

Summary

  • Turn on Cache Components with cacheComponents: true. Rendering is then dynamic unless you opt in to caching.
  • "use cache" caches a function, a component or every export of a file. Cached functions must be async.
  • The cache key is built from the function, its serializable arguments and closed-over values.
  • cacheLife sets stale, revalidate and expire. Between the last two, the entry is served old while refreshing in the background.
  • cacheTag labels entries so mutations can invalidate them later.
  • Request data such as cookies is read outside the cached scope and passed in as an argument.
  • Static and cached parts form the shell, and dynamic parts sit inside <Suspense> and stream in.

Next, learn how to refresh cached data when something changes in Revalidating Data.