react如何鉴定
React 组件性能优化方法
使用 React.memo 对函数组件进行浅比较优化,避免不必要的重新渲染。适用于 props 未变化的场景。
const MemoizedComponent = React.memo(function MyComponent(props) {
/* 使用 props 渲染 */
});
使用 useMemo 缓存计算结果
对于耗时的计算操作,通过 useMemo 进行缓存,仅在依赖项变化时重新计算。
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
使用 useCallback 缓存函数
避免子组件因回调函数引用变化导致的无效渲染,使用 useCallback 维持函数稳定性。
const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);
虚拟化长列表渲染
对于大型列表数据,采用 react-window 或 react-virtualized 实现虚拟滚动,仅渲染可视区域内容。
import { FixedSizeList as List } from 'react-window';
const Row = ({ index, style }) => (
<div style={style}>Row {index}</div>
);
const Example = () => (
<List height={150} itemCount={1000} itemSize={35} width={300}>
{Row}
</List>
);
代码分割与懒加载
通过 React.lazy 和 Suspense 实现组件级代码分割,减少初始加载体积。
const OtherComponent = React.lazy(() => import('./OtherComponent'));
function MyComponent() {
return (
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</Suspense>
);
}
使用 Profiler API 进行性能检测
通过 React DevTools 或编程式 Profiler 组件测量渲染时间和成本。
<Profiler id="Navigation" onRender={callback}>
<Navigation {...props} />
</Profiler>
避免内联函数和对象
减少在渲染方法中创建新的函数/对象,防止子组件无意义的重新渲染。
// 避免
<Button onClick={() => handleClick(id)} />
// 推荐
const handleClick = useCallback((id) => () => {
/* 处理逻辑 */
}, []);
使用不可变数据
配合 Immutable.js 或 Immer 管理状态,便于快速比较数据变化,优化 shouldComponentUpdate 逻辑。

import produce from 'immer';
const nextState = produce(currentState, draft => {
draft.todos[1].done = true;
});






