Server, client and data · Lesson 8 of 16
Caching and revalidation
"use cache", cacheLife and cacheTag, and refreshing data after changes.
If every visit to the courses page queries the database, it's slow and costly. A cache stores the result and reuses it. The hard question is always when the stored copy is stale and must refresh.
In Next.js 16 with Cache Components (cacheComponents: true in next.config.ts), anything not cached is fetched per request, and you explicitly mark what to cache with "use cache":
// lib/courses.ts
import { cacheLife, cacheTag } from "next/cache"
export async function getCatalog() {
"use cache"
cacheLife("hours") // a built-in profile: refresh in the background every hour or so
cacheTag("courses") // a label we can invalidate later
return db.course.findMany({ where: { published: true } })
}// app/admin/actions.ts: after an admin edits a course
"use server"
import { revalidatePath, updateTag } from "next/cache"
export async function publishCourse(id: string) {
await db.course.update({ where: { id }, data: { published: true } })
updateTag("courses") // expire everything tagged "courses" now (read-your-own-writes)
revalidatePath("/courses") // and re-render this path
}| Function | What it does |
|---|---|
"use cache" | cache a function's, component's or page's output |
cacheLife("hours") | how long the copy stays fresh |
cacheTag("courses") | a label for invalidation |
updateTag(tag) | expire now from a server action; the user sees their change |
revalidateTag(tag, "max") | mark stale; serve old until the new is ready |
revalidatePath("/courses") | rebuild a specific path |
Spot the bug
An admin adds a course, but the courses page only shows it an hour later. What's wrong?
Quick question
A student renames themself in settings and must see the new name immediately after saving. What do you use in the server action?
Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.