Chapter 2 · Practice 2 of 6
Cache data and UI with use cache and always set a cacheLife
Why it matters
Caching is now opt in, so you decide what is reused and for how long. Add the 'use cache' directive at the top of an async function or component to cache its result. Arguments and captured values become part of the cache key automatically.
- Data level: cache shared queries like
getProducts(). - UI level: cache a whole component.
Pair every cache directive with cacheLife, using a profile such as 'hours', 'days' or 'max', or a custom object. Without it the implicit default profile applies, which may not match how fresh the data needs to be.
Example
import { cacheLife, cacheTag } from 'next/cache';
export async function getProducts() {
'use cache';
cacheLife('hours');
cacheTag('products');
return db.query('SELECT id, name, price FROM products');
}