通过移动状态优化重新渲染

发布: (2025年12月30日 GMT+8 22:58)
3 min read
原文: Dev.to

Source: Dev.to

介绍

一种提升性能并减少不必要重新渲染的方法是降低状态的层级,尤其是当它只影响组件树的特定部分时。

例如,考虑一个父组件,它有一个按钮用于更改 count 状态。将此状态的更改移动到单独的组件中,我们可以防止整个父组件重新渲染。

之前的写法(存在性能问题)

import { useState } from 'react';
import { data } from '../../../../data';
import List from './List';

const App = () => {
  const [people, setPeople] = useState(data);
  const [count, setCount] = useState(0);

  return (
    
       setCount(count + 1)}
        style={{ marginBottom: '1rem' }}
      >
        count {count}
      
      
    
  );
};
export default App;

在这种写法中,每次 count 状态变化时,整个 App 组件(包括 List 组件)都会重新渲染,这效率不高。

Profiler Highlight

解决方案:将计数按钮移动到单独的 Counter 组件

import { useState } from 'react';
import { data } from '../../../../data';
import List from './List';
import Counter from './Counter';

const App = () => {
  const [people, setPeople] = useState(data);

  return (
    
      
      
    
  );
};
export default App;

通过将计数按钮抽取到自己的 Counter 组件中,只有该组件在计数变化时重新渲染,其他 UI 部分保持不变。

更新后的 Counter 组件

import { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);

  return (
     setCount(count + 1)}
      style={{ marginBottom: '1rem' }}
    >
      count {count}
    
  );
};

export default Counter;

React Profiler

在 React Profiler 中,你会看到只有 Counter 组件在点击按钮时重新渲染,List 组件及其子组件(例如 Person)则不会重新渲染。

Profiler 截图

Profiler Settings 1

Profiler Settings 2

Profiler Settings 3

Profiler Settings 4

Profiler Settings 5

总结

通过将影响特定 UI 元素(如计数按钮)的状态拆分到独立组件中,我们可以减少不必要的重新渲染,从而提升性能。

Back to Blog

相关文章

阅读更多 »