Sikau

Next.js · Day 15 · about 30 min

Caching and revalidation

"use cache", cacheLife and fresh data on demand.

Don't cook the same dish twice

If the menu changes once a day, querying the database on every visit is wasted work. Next.js can cache a function's result or a whole component, serve it instantly, and refresh it on a schedule or when you say the data changed (revalidation).

Cache Components (Next.js 16)

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

// lib/menu.js
import { cacheLife, cacheTag } from "next/cache";

export async function getMenu() {
  "use cache";
  cacheLife("hours");
  cacheTag("menu");
  return db.query("SELECT * FROM dishes");
}

// app/actions.js — after editing a dish
"use server";
import { updateTag } from "next/cache";

export async function renameDish(id, name) {
  await db.update(id, name);
  updateTag("menu");
}
  • Cached output becomes part of the page's static shell, sent instantly; uncached data streams in inside <Suspense>.
  • Don't cache per-user data (carts, profiles) in a shared cache.
  • Reading cookies, headers or searchParams makes that part dynamic — keep it inside Suspense.

The rest of this lesson

  • Choosing what to cacheexplain
  • Static shell and dynamic holesexplain
  • Cached or not?predict
  • Cache it?match
  • Editing a dishorder
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 19 lessons of Next.js