服务端组件缓存优化策略踩坑记录
最近在实践中使用React Server Components时,发现性能问题主要集中在重复渲染和数据获取上。分享几个实用的缓存优化策略。
问题场景
在构建一个电商商品列表页面时,发现每次路由切换都会重新fetch数据,即使数据完全相同。
解决方案
1. 使用React Cache API
// server-components.js
import { cache } from 'react';
const fetchProductList = cache(async (category) => {
const response = await fetch(`/api/products?category=${category}`);
return response.json();
});
export default function ProductList({ category }) {
const products = use(fetchProductList(category));
return <div>{products.map(p => <div key={p.id}>{p.name}</div>)}</div>;
}
2. 自定义缓存装饰器
// cacheDecorator.js
export function withCache(ttl = 5000) {
const cache = new Map();
return (target, key, descriptor) => {
const originalMethod = descriptor.value;
descriptor.value = async function(...args) {
const cacheKey = JSON.stringify(args);
const cached = cache.get(cacheKey);
if (cached && Date.now() - cached.timestamp < ttl) {
return cached.data;
}
const result = await originalMethod.apply(this, args);
cache.set(cacheKey, { data: result, timestamp: Date.now() });
return result;
};
};
}
性能对比
- 优化前:平均响应时间 1200ms,重复请求率 85%
- 优化后:平均响应时间 320ms,重复请求率 95%以上
实践建议
避免在Server Component中使用全局状态,优先使用React Cache API进行缓存。
踩坑提醒:缓存策略需要根据业务场景调整,过度缓存可能导致数据不一致问题。

讨论