Next.js course Β· Module 9: Integrations and Advanced Features
use cache - A new era of caching in Next.js 16
In this lesson7
In the server rooms of Metropolis Quantum 2150, where every millisecond counts, you will learn about the revolutionary caching API that appeared as an experiment in Next.js 15 and became part of Cache Components in Next.js 16. The use cache directive replaces the deprecated unstable_cache and brings a much more intuitive way to manage the cache.
What is the use cache directive?
use cache is a new directive (similar to use server or use client) that marks functions or entire files as cacheable. Next.js automatically manages the cache lifecycle and revalidation.
Enabling Cache Components
To use use cache, you first need to enable the cacheComponents option in your configuration:
// next.config.js
module.exports = {
cacheComponents: true,
};In Next.js 15 (in canary releases), the same feature was hidden behind the experimental experimental.dynamicIO and experimental.useCache flags. Next.js 16 removed both flags, and cacheComponents is not just a new name: it turns on the whole Cache Components model, which can surface build errors when a route reads uncached data outside a <Suspense> boundary.
Basic use cache usage
Caching a single function
// app/lib/data.ts
async function getProducts() {
'use cache';
const response = await fetch('https://api.quantum-store.com/products');
return response.json();
}Caching an entire file
// app/lib/cached-data.ts
'use cache';
export async function getUsers() {
const response = await fetch('https://api.quantum-store.com/users');
return response.json();
}
export async function getOrders() {
const response = await fetch('https://api.quantum-store.com/orders');
return response.json();
}cacheLife - Controlling cache lifetime
The cacheLife function lets you precisely define how long data should be stored in the cache.
Predefined profiles
Next.js ships with built-in time profiles:
import { cacheLife } from 'next/cache';
async function getNews() {
'use cache';
cacheLife('minutes'); // cache for a few minutes
return fetch('https://api.quantum-news.com/latest').then(r => r.json());
}
async function getStaticContent() {
'use cache';
cacheLife('days'); // cache for days
return fetch('https://api.quantum-cms.com/static').then(r => r.json());
}
async function getRealTimeData() {
'use cache';
cacheLife('seconds'); // cache for seconds
return fetch('https://api.quantum-sensors.com/data').then(r => r.json());
}Available built-in profiles:
| Profile | stale | revalidate | expire | Description |
|---|---|---|---|---|
default | 5min | 15min | never | The profile used when you do not call cacheLife |
seconds | 30s | 1s | 60s | For rapidly changing data |
minutes | 5min | 1min | 1h | For data updated every few minutes |
hours | 5min | 1h | 1d | For hourly data |
days | 5min | 1d | 1w | For rarely changing data |
weeks | 5min | 1w | 30d | For near-static data |
max | 5min | 30d | 1y | Maximum cache duration |
Custom cacheLife configurations
You can define your own profiles in next.config.js:
// next.config.js
module.exports = {
cacheComponents: true,
cacheLife: {
quantumFast: {
stale: 10, // seconds - time when data is "fresh"
revalidate: 30, // seconds - time after which to revalidate in background
expire: 300, // seconds - maximum lifetime
},
quantumProducts: {
stale: 60,
revalidate: 300,
expire: 3600,
},
},
};Using a custom profile:
import { cacheLife } from 'next/cache';
async function getQuantumProducts() {
'use cache';
cacheLife('quantumProducts');
return fetch('https://api.quantum-store.com/products').then(r => r.json());
}Inline configuration
You can also define the configuration directly:
import { cacheLife } from 'next/cache';
async function getCriticalData() {
'use cache';
cacheLife({
stale: 5,
revalidate: 15,
expire: 60,
});
return fetch('https://api.quantum-critical.com/data').then(r => r.json());
}cacheTag - Tagging and selective revalidation
cacheTag lets you label the cache with tags that can later be used for selective revalidation.
Basic tagging
import { cacheTag, cacheLife } from 'next/cache';
async function getProduct(id: string) {
'use cache';
cacheTag(`product-${id}`);
cacheLife('hours');
return fetch(`https://api.quantum-store.com/products/${id}`).then(r => r.json());
}
async function getCategory(slug: string) {
'use cache';
cacheTag('categories', `category-${slug}`);
cacheLife('days');
return fetch(`https://api.quantum-store.com/categories/${slug}`).then(r => r.json());
}Revalidating by tags
// app/actions/revalidate.ts
'use server';
import { revalidateTag, updateTag } from 'next/cache';
export async function updateProduct(id: string, data: ProductData) {
// Update product in the database
await db.products.update(id, data);
// Revalidate cache for this product
updateTag(`product-${id}`);
}
export async function refreshAllCategories() {
// Revalidate all categories at once
revalidateTag('categories', 'max');
}In Next.js 16 you have two functions to choose from. updateTag works only in Server Actions and expires the cache right away, so the user sees their change within the same request. revalidateTag with the second argument 'max' marks the data as stale and refreshes it in the background, serving the old version until then; the single-argument form is deprecated.
Practical example - Quantum Store Dashboard
// app/lib/dashboard-data.ts
import { cacheTag, cacheLife } from 'next/cache';
// Product data - cache for hours, tagged
export async function getDashboardProducts() {
'use cache';
cacheTag('dashboard', 'products');
cacheLife('hours');
const response = await fetch('https://api.quantum-store.com/dashboard/products');
return response.json();
}
// Sales stats - cache for minutes (frequent updates)
export async function getSalesStats() {
'use cache';
cacheTag('dashboard', 'sales');
cacheLife('minutes');
const response = await fetch('https://api.quantum-store.com/dashboard/sales');
return response.json();
}
// User data - cache for days
export async function getUserStats() {
'use cache';
cacheTag('dashboard', 'users');
cacheLife('days');
const response = await fetch('https://api.quantum-store.com/dashboard/users');
return response.json();
}// app/actions/dashboard-actions.ts
'use server';
import { updateTag } from 'next/cache';
export async function refreshDashboard() {
// Revalidate the entire dashboard
updateTag('dashboard');
}
export async function refreshSalesOnly() {
// Revalidate only sales
updateTag('sales');
}// app/dashboard/page.tsx
import { getDashboardProducts, getSalesStats, getUserStats } from '@/lib/dashboard-data';
import { refreshDashboard, refreshSalesOnly } from '@/actions/dashboard-actions';
export default async function DashboardPage() {
const [products, sales, users] = await Promise.all([
getDashboardProducts(),
getSalesStats(),
getUserStats(),
]);
return (
<div className="quantum-dashboard">
<header className="flex justify-between items-center">
<h1>Dashboard Quantum Store</h1>
<div className="flex gap-2">
<form action={refreshSalesOnly}>
<button type="submit">Refresh sales</button>
</form>
<form action={refreshDashboard}>
<button type="submit">Refresh all</button>
</form>
</div>
</header>
<div className="grid grid-cols-3 gap-6">
<ProductsWidget data={products} />
<SalesWidget data={sales} />
<UsersWidget data={users} />
</div>
</div>
);
}Differences between use cache and unstable_cache
| Feature | use cache | unstable_cache |
|---|---|---|
| Syntax | Directive | Wrapper function |
| Time configuration | cacheLife() | revalidate option |
| Tagging | cacheTag() | tags option |
| Scope | Function or file | Function only |
| Status | Stable since Next.js 16 (Cache Components) | Replaced by use cache in Next.js 16 |
Migrating from unstable_cache
Before (old way):
import { unstable_cache } from 'next/cache';
const getCachedProducts = unstable_cache(
async () => {
return fetch('https://api.com/products').then(r => r.json());
},
['products'],
{ revalidate: 3600, tags: ['products'] }
);After (new way):
import { cacheTag, cacheLife } from 'next/cache';
async function getProducts() {
'use cache';
cacheTag('products');
cacheLife('hours');
return fetch('https://api.com/products').then(r => r.json());
}Summary
The use cache directive in Next.js 16 introduces:
- Simpler syntax - declarative caching with a directive
- Flexible time control -
cacheLifewith profiles or custom configurations - Selective revalidation -
cacheTagfor precise refresh - Better performance - optimized cache management
In Metropolis Quantum 2150, where data flows at the speed of light, proper caching is the difference between a lightning-fast application and one that barely keeps up. Master use cache and your Next.js applications will run at top speed!
Code for this lesson: App.tsx
import React, { useState } from 'react';
// use cache - New era of caching in Next.js 16
// Demonstration of 'use cache' directive and its configuration
export default function UseCacheDemo() {
const [cacheStrategy, setCacheStrategy] = useState('default');
const [data, setData] = useState<any>(null);
const [isFetching, setIsFetching] = useState(false);
const strategies = [
{ id: 'default', label: 'Default Cache', ttl: '30s', description: 'Default caching with revalidation every 30s' },
{ id: 'force-cache', label: 'Force Cache', ttl: 'infinite', description: 'Data is cached permanently' },
{ id: 'no-store', label: 'No Store', ttl: '0', description: 'No caching - always fresh data' },
{ id: 'revalidate', label: 'Revalidate', ttl: '60s', description: 'ISR - revalidation every 60 seconds' },
];
// TODO: Implement fetchWithCache - simulate different caching strategies
// TODO: Show differences in response times for different strategies
return (
<div style={{ background: '#0f0f23', minHeight: '100vh', padding: 20, color: '#e0e0e0', fontFamily: 'monospace' }}>
<h1 style={{ color: '#64ffda' }}>use cache - Next.js 16</h1>
{/* TODO: Caching strategy selector */}
{/* TODO: "Fetch data" button */}
{/* TODO: Display response time and data */}
{/* TODO: Strategy comparison */}
</div>
);
}Spotted a mistake in this lesson?