Next.js 缓存策略
Next.js 15 提供了强大的缓存机制,理解这些缓存策略对于构建高性能应用至关重要。
缓存概述
Next.js 的缓存机制分为多个层次:
数据缓存
fetch 缓存
// 默认:缓存到路由段
async function getData() {
const res = await fetch('https://api.example.com/data');
return res.json();
}
// 不缓存
fetch('https://api.example.com/data', { cache: 'no-store' });
// 强制重新验证
fetch('https://api.example.com/data', {
next: { revalidate: 3600 } // 每小时重新验证
});
// 仅使用缓存
fetch('https://api.example.com/data', {
cache: 'force-cache'
});
缓存选项
// revalidate: 重新验证秒数
// - 0: 不缓存
// - 数字: 缓存秒数
// fetch(url, { next: { revalidate: 60 } })
// tag: 缓存标签,用于手动重新验证
fetch(url, {
next: {
tags: ['posts']
}
});
路由缓存
静态页面缓存
// app/posts/page.tsx
export default async function PostsPage() {
// 首次请求时获取数据并缓存
const posts = await fetchPosts();
return (
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
// 手动重新验证缓存
import { revalidateTag, revalidatePath } from 'next/cache';
export async function refreshData() {
// 重新验证特定标签
revalidateTag('posts');
// 重新验证特定路径
revalidatePath('/posts');
}
动态函数缓存
unstable_cache
import { unstable_cache } from 'next/cache';
const getCachedData = unstable_cache(
async (id: string) => {
const res = await fetch(`/api/data/${id}`);
return res.json();
},
['data-cache'], // 缓存键
{
revalidate: 3600, // 重新验证时间
tags: ['data'] // 缓存标签
}
);
客户端缓存
useSWR
'use client';
import useSWR from 'swr';
const fetcher = (url: string) => fetch(url).then(res => res.json());
function Profile() {
const { data, error, isLoading } = useSWR('/api/user', fetcher);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error</div>;
return <div>Hello, {data.name}</div>;
}
最佳实践
1. 合理选择缓存策略
// 频繁变化的数据:不缓存
fetch('/api/stats', { cache: 'no-store' });
// 定期更新的数据:ISR
fetch('/api/products', {
next: { revalidate: 60 }
});
// 几乎不变的数据:静态缓存
fetch('/api/categories', { cache: 'force-cache' });
2. 使用缓存标签
// 数据获取时添加标签
fetch('/api/posts', {
next: { tags: ['posts'] }
});
// 更新时清除缓存
import { revalidateTag } from 'next/cache';
// 在 Server Action 中
export async function createPost(formData: FormData) {
await createPostAPI(formData);
revalidateTag('posts');
}
总结
Next.js 的缓存机制:
- 数据缓存:fetch 请求结果缓存
- 路由缓存:静态页面结果缓存
- 动态函数缓存:unstable_cache
- 客户端缓存:SWR、React Query
合理使用缓存可以显著提升应用性能。