性能 Optimization
Identifying and fixing React 性能 bottlenecks 使用 profiling and optimization 技巧.
你将学到
- Using React Profiler 到 identify bottlenecks
- Reducing 不必要 re-渲染
- Virtualizing 长列表 for 性能
- Debouncing, throttling, and deferring 工作
概念讲解
Identify Before You Optimize
The first rule of performance optimization is measure before you optimize. React DevTools Profiler shows you exactly which components re-render, how long each render takes, and what caused the re-render. Record a profile while interacting with your app, look for components that re-render unnecessarily or take a long time, and focus your optimization efforts there. Do not guess — profile and let the data guide you.
Reducing Re-renders
Unnecessary re-renders are the most common React performance issue. A parent re-rendering causes all children to re-render by default, even if their props have not changed. Fix this with React.memo for expensive children, useMemo and useCallback to stabilize props, and by keeping state as local as possible so that updates do not cascade through the tree. Split large components into smaller ones so that a state change in one part does not re-render the entire subtree.
Virtualizing Long Lists
Rendering thousands of DOM nodes is slow — the browser struggles to lay out and paint them all. Virtualization (or windowing) renders only the visible items plus a small buffer, replacing the rest with empty space. As the user scrolls, the items are recycled. Libraries like react-window and @tanstack/react-虚拟 handle this efficiently. For any list with more than a few hundred items, virtualization is essential for smooth scrolling.
Debouncing and Throttling
Some events fire very frequently: scroll, resize, mousemove, and text input. If your handler does expensive work on every event, the UI will lag. Debouncing delays the handler until the events stop coming for a specified delay (useful for search input). Throttling limits the handler to fire at most once per specified interval (useful for scroll handlers). Use the useDeferredValue hook (React 18) to defer expensive rendering without blocking input, and startTransition to mark non-urgent state updates.
示例代码
import { useState, useMemo, useDeferredValue, memo } from "react";
// Memoized row — only re-renders when its data changes.
const Row = memo(function Row({ item }) {
return <tr><td>{item.id}</td><td>{item.name}</td><td>{item.value}</td></tr>;
});
function SearchableTable({ items }) {
const [query, setQuery] = useState("");
// useDeferredValue lets the input stay responsive while filtering lags behind.
const deferredQuery = useDeferredValue(query);
const isStale = query !== deferredQuery;
// Memoized filtering — only recomputes when items or deferredQuery change.
const filtered = useMemo(
() => items.filter(i => i.name.toLowerCase().includes(deferredQuery.toLowerCase())),
[items, deferredQuery]
);
return (
<div>
<input
value={query}
onChange={e => setQuery(e.target.value)}
placeholder="Search..."
style={{ opacity: isStale ? 0.7 : 1 }}
/>
<table>
<tbody>
{filtered.map(item => <Row key={item.id} item={item} />)}
</tbody>
</table>
</div>
);
}
useDeferredValue keeps 输入 responsive 虽然 expensive 筛选 catches 上. useMemo caches 筛选列表. memo prevents 行 re-渲染当 仅查询更改.
动手试一试
- Code Diff
Compare optimized and unoptimized 组件 versions.
- Code Minifier
Minified code 运行 faster — see impact on 你的 bundle.
常见错误
错误写法
Optimizing prematurely 不使用 profiling 首先
正确做法
Use React DevTools Profiler 到 identify 实际 bottlenecks 之前添加 memo, useMemo, or useCallback. Premature optimization 添加复杂度 and 能偶数慢 things 下使用不必要 comparisons.
错误写法
渲染 thousands 的列表项 不使用 virtualization
正确做法
For 列表使用更多 than 少数 hundred 项, use virtualization (react-window or @tanstack/react-虚拟). 渲染所有项 创建 thousands 的 DOM 节点那个浏览器 cannot handle smoothly.
练习 性能 Optimization
1 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。