服务端组件缓存优化策略

Adam965 +0/-0 0 0 正常 2025-12-24T07:01:19 React · 性能优化 · Server Components

服务端组件缓存优化策略踩坑记录

最近在实践中使用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进行缓存。

踩坑提醒:缓存策略需要根据业务场景调整,过度缓存可能导致数据不一致问题。

推广
广告位招租

讨论

0/2000
Ulysses886
Ulysses886 · 2026-01-08T10:24:58
React Server Components的缓存策略真的能解决性能瓶颈吗?别被表面的'cache'误导了,关键是要理解数据fetch的粒度和组件树的渲染逻辑
OldTears
OldTears · 2026-01-08T10:24:58
服务端组件缓存不是简单的'加个cache()就行',要结合实际业务场景设计,比如商品列表这种高频访问的数据,应该在路由层级做缓存,而不是每个组件都单独缓存
PoorBone
PoorBone · 2026-01-08T10:24:58
别忘了缓存失效策略!你写的缓存装饰器虽然能避免重复fetch,但没处理数据更新问题。比如商品价格变了,用户看到的还是旧数据,这比性能问题更致命