20+ 个实用技巧,让您的 React 应用飞起来。学习记忆化、代码分割、渲染优化等。
# React 性能优化指南
## 为什么性能很重要
- 53% 的移动用户会在加载时间超过 3 秒时离开网站
- 更好的用户体验带来更高的转化率
- Google 使用 Core Web Vitals 进行排名
## 1. 使用 useMemo 和 useCallback
### useMemo - 记忆化昂贵计算
```tsx
function ExpensiveComponent({ data }) {
const processedData = useMemo(() => {
return data.map(item => expensiveOperation(item));
}, [data]);
return <List data={processedData} />;
}
```
### useCallback - 记忆化函数
```tsx
function ParentComponent() {
const handleClick = useCallback((id) => {
console.log('Clicked:', id);
}, []);
return <Child onClick={handleClick} />;
}
```
## 2. 代码分割
### 动态导入
```tsx
const HeavyComponent = dynamic(() => import('./HeavyComponent'), {
loading: () => <p>Loading...</p>,
ssr: false
});
```
### 路由级分割
```tsx
const Home = lazy(() => import('./pages/Home'));
const About = lazy(() => import('./pages/About'));
function App() {
return (
<Routes>
<Route path="/" element={<Suspense fallback={<Loading />}><Home /></Suspense>} />
</Routes>
);
}
```
## 3. 虚拟化
### react-window 长列表
```tsx
import { FixedSizeList } from 'react-window';
function VirtualList({ items }) {
const Row = ({ index, style }) => (
<div style={style}>{items[index].name}</div>
);
return (
<FixedSizeList
height={300}
itemCount={items.length}
itemSize={50}
width="100%"
>
{Row}
</FixedSizeList>
);
}
```
## 4. 优化重渲染
### React.memo
```tsx
const Button = React.memo(function Button({ onClick, children }) {
return <button onClick={onClick}>{children}</button>;
});
```
## 5. 图片优化
### Next.js Image
```tsx
import Image from 'next/image';
function MyPage() {
return (
<Image
src="/hero.jpg"
alt="Hero"
width={1200}
height={600}
priority
/>
);
}
```
## 性能检查清单
- [ ] 使用生产构建
- [ ] 启用压缩
- [ ] 实现代码分割
- [ ] 优化图片
- [ ] 使用 CDN
- [ ] 启用缓存
- [ ] 监控 Core Web Vitals
💬 评论功能尚未配置
请设置 NEXT_PUBLIC_WALINE_SERVER_URL 环境变量