组件优化
React.memo():缓存函数组件,避免不必要的重新渲染
const MyComponent = React.memo(function MyComponent(props) {
/* 只在 props 改变时重新渲染 */
});
PureComponent:类组件的浅比较优化
class MyComponent extends React.PureComponent {
// 自动进行 props 和 state 的浅比较
}
状态管理优化
- 状态提升/下放:将状态放在合适的组件层级
- 使用 useState 的函数式更新:避免依赖旧状态
// 避免
setCount(count + 1);
// 推荐
setCount(prev => prev + 1);
函数/事件处理优化
useCallback:缓存回调函数
const handleClick = useCallback(() => {
// 函数逻辑
}, [dependency]);
useMemo:缓存计算结果
const expensiveValue = useMemo(() => {
return computeExpensiveValue(a, b);
}, [a, b]);
列表渲染优化
Key 的合理使用:使用稳定、唯一的 key
{
items.map(item => <ListItem key={item.id} item={item} />);
}
虚拟列表:对于长列表使用 react-window 或 react-virtualized
import { FixedSizeList } from "react-window";
代码分割
React.lazy + Suspense:懒加载组件
const OtherComponent = React.lazy(() => import("./OtherComponent"));
function MyComponent() {
return (
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</Suspense>
);
}
依赖优化
useEffect 依赖项:精确指定依赖数组
useEffect(() => {
// 副作用逻辑
}, [dependency1, dependency2]); // 明确列出所有依赖
Context 优化
拆分 Context:避免大对象导致的重新渲染
// 将大的 Context 拆分成多个小的 Context
const UserContext = React.createContext();
const ThemeContext = React.createContext();
渲染过程优化
防抖/节流:控制频繁触发的事件
const throttledFunction = useRef(throttle(callback, 1000));
避免内联对象/函数:
// 避免
<Component style={{ color: "red" }} onClick={() => {}} />;
// 推荐
const style = useMemo(() => ({ color: "red" }), []);
const handleClick = useCallback(() => {}, []);
开发工具使用