shinyaz.com

Next.js 'use cache' directive enables component-level caching

1 min read

I was looking into caching strategies for Server Component data fetching in Next.js when I found the "use cache" directive alongside the familiar fetch(..., { next: { revalidate: 60 } }) pattern. The surprise: it works on any async function or Server Component, not just fetch calls:

async function getData() {
  "use cache";
  const res = await fetch("https://api.example.com/data");
  return res.json();
}

With the old pattern, you had to set cache options on each fetch call individually. "use cache" works at the function level — so database queries, external API wrappers, or any async logic can be cached the same way. Cache duration is controlled with cacheLife:

import { cacheLife } from "next/cache";
 
async function getData() {
  "use cache";
  cacheLife("hours");
  // ...
}

Predefined profiles: "seconds", "minutes", "hours", "days", "weeks", "max". You can also define custom profiles in next.config.ts.

Share this post

Shinya Tahara

Shinya Tahara

Solutions Architect @ AWS

I'm a Solutions Architect at AWS, providing technical guidance primarily to financial industry customers. I share learnings about cloud architecture and AI/ML on this blog.