生态层性能
Query 缓存、代码分割回顾。
25 分钟
生态层性能
React 核心课讲过 memo、lazy;生态选型会直接影响 bundle 大小、请求次数、缓存命中率。本课从 Query 缓存、代码分割、UI 库体积三方面 回顾 + 落地检查清单。
学习目标
- 串联 TanStack Query 缓存策略与感知性能
- 会用
React.lazy/ Next.js dynamic 做路由级分割 - 识别 UI 库、Motion、整包 import 的常见坑
Query 层性能
| 手段 | 效果 |
|---|---|
| 合理 staleTime | 减少重复 GET |
| prefetch(hover 链接触发) | 导航近乎瞬时 |
| select 切片 | 组件只订阅用到的字段 |
| placeholderData | 切页不白屏 |
useQuery({
queryKey: ["track", slug],
queryFn: fetchTrack,
select: (data) => data.lessons, // 仅 lessons 变才触发本组件
});
与 rxe-query 一致:少请求 + 少重渲染。
代码分割
Vite / CRA:
const AdminPanel = lazy(() => import("./AdminPanel"));
<Suspense fallback={<Spinner />}>
<AdminPanel />
</Suspense>
Next.js App Router:
import dynamic from "next/dynamic";
const Chart = dynamic(() => import("./Chart"), { ssr: false, loading: () => <p>…</p> });
管理台、图表、富编辑器 适合按路由或 tab 懒加载。详见 nextjs-essentials 的 bundle 与 RSC 分工。
UI 与 Motion 体积
- MUI:按路径 import
@mui/material/Button,忌import * from '@mui/material' - shadcn:只 add 用到的组件
- framer-motion:大页动画多时用 LazyMotion + domAnimation 减 feature bundle
- 图标:单图标 import,勿整包 react-icons 全扫
列表与虚拟化
课时上百条时,DOM 节点过多会卡 scroll。用 @tanstack/react-virtual 或窗口化列表;动画层避免给上千 motion.div 同时 layout。
测量先于优化
- Lighthouse / Web Vitals(LCP、INP)
- Next.js Bundle Analyzer 或
vite-bundle-visualizer - React DevTools Profiler 找 无谓重渲染
testing-essentials 的 CI 可门禁 Lighthouse 预算(选做)。