'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.
API reference · use cacheRead docs ↗

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
Request log
TimeEntry ageServedDB
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'Bad

50 DB queries

oldest: 0m
cacheLife('hours')Good

0 DB queries

oldest: -revalidate ~1h

Where the directive goes

Move the directive, then send a few requests.

Scope of 'use cache'
app/dashboard/page.tsxfunction
    Rendered pageRequest 0
    Headerstatic
    Stats
    getData()-
    getVisitors()-
    Inbox

    -

    DB calls: -total: 0

    Why 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 revalidate old
    • cookies() and headers() are banned inside the scope
    • File scope caches every export in the file