Course outline · 0% complete

0/29 lessons0%

Course overview →

The caching mental model

lesson 4-2 · ~10 min · 12/29

Fresh by default

In the current Next.js model, a plain fetch in a server component is not cached between requests. Every visitor triggers a real request, so data is always fresh, at the cost of speed and load on the data source.

When the data changes rarely (a blog post, a product list), you can opt into caching and tell Next.js how long the copy stays valid:

// re-fetch at most once every 60 seconds
const res = await fetch(url, { next: { revalidate: 60 } });

Between refreshes, every visitor is served the saved result instantly. This one option is the seed of the rendering strategies in Unit 7.

Three layers, one table

LayerLifetimeWhat it saves you
Request memoizationone renderduplicate fetches to the same URL in one page render
Data cache (revalidate)seconds to days, you choosere-fetching the same data for every visitor
Full-page prerenderuntil rebuilt or revalidatedre-rendering the whole page (Unit 7)

Mental shortcut: memoization dedupes within a request, caching reuses across requests. When something looks stale, ask which layer is holding the old copy.

Quiz

A product page fetches prices with { next: { revalidate: 3600 } }. The price changes in the database 5 minutes after the last fetch. What do visitors see for the rest of the hour?

Code exercise · javascript

Server components often reshape API data before rendering. Practice the pure-logic part (runnable here, no JSX needed). Write latestTitles(posts, n): return the titles of the n most recent posts, newest first. Dates are "YYYY-MM-DD" strings, so localeCompare sorts them correctly, a trick from Advanced JavaScript. Do not mutate the input array.