'use cache' and cacheLife
Cache async work with 'use cache'; set its lifetime with cacheLife.
Next.js docsnextjs.org
Marks a function or component for caching. Part of Next.js Cache Components.
From next-cache-components, “use cache Directive” and “Cache Profiles”.
The cache clock
Drag the clock, then press Request or Play.
getData() over 30 h1h / 2h / 1d- HIT
- Stale + refresh
- MISS
No cache
'use cache'
no cache: 0 queriescached: 0 queriesblocked: 0
| Time | Entry age | Served | DB |
|---|
import { cacheLife } from 'next/cache'
async function getData() {
'use cache'
cacheLife({ stale: 3600, revalidate: 7200, expire: 86400 })
return fetch('/api/data')
}
One profile, 50 visits
Pick a profile and a visit rate.
No
'use cache'Bad50 DB queries
oldest: 0mcacheLife('hours')Good0 DB queries
oldest: -revalidate ~1h
Where the directive goes
Move the directive, then send a few requests.
app/dashboard/page.tsxfunction
Rendered pageRequest 0
Headerstatic
Stats
getData()-getVisitors()-Inbox
-
DB calls: -total: 0Why it matters, pros and cons
Why it matters
Most async work repeats its answer. cacheLife says how old it may get.
Pros
- One query per window, not per visit
- Stale hits stay instant while refreshing
- Keys come from arguments, no key arrays
Cons
- Data can be up to
revalidateold cookies()andheaders()are banned inside the scope- File scope caches every export in the file