优化 React 应用程序以实现最佳性能简介 1. 优化大型列表 2. useMemo 3. 代码拆分 4. React 延迟加载节流和去抖动与我联系结论

2025-06-04

优化 React 应用程序以实现最佳性能

介绍

1. 优化大列表

2. useMemo

3. 代码拆分

4. React 延迟加载

节流和去抖

与我联系

结论

介绍

我写 React 代码已经三年多了。然而,最初我并没有关注 React 的性能优化。很多时候,技术债越积越多,性能优化也变得越来越困难。

从一开始就专注于优化是相当困难的,但您可以不时安排优化,以避免巨大的技术债务。

我们将研究一些 React 的优化技术。这些技术可以在你编写代码时实现。关键在于选择哪种方法。

那么,让我们开始吧。

1. 优化大列表

React 中有很多组件,渲染列表非常常见。渲染大型列表非常困难,因为它会导致渲染速度缓慢和内存占用过高。虚拟化是解决此类问题的最佳方法。它只渲染可见的列表,其他项目在需要时再渲染。

React Window 和 React Virtualized 是虚拟化列表中流行的库。它们仅渲染视口中可见的项目,从而显著减少了任何给定时间渲染的 DOM 节点数量。

以下是 React Window 的一个示例:

    import { FixedSizeList as List } from 'react-window';

    const MyList = ({ items }) => (
      <List
        height={500} // Height of the container
        itemCount={items.length} // Total number of items
        itemSize={35} // Height of each item
        width={300} // Width of the container
      >
        {({ index, style }) => (
          <div style={style}>
            {items[index]}
          </div>
        )}
      </List>
    );
Enter fullscreen mode Exit fullscreen mode

2. useMemo

useMemo 是一个 React hook,用于记忆计算结果。因此,除非依赖项发生变化,否则它不允许对计算进行多次处理。当函数或计算开销较大且不应在每次渲染时重新执行时,此功能有助于优化性能。

useMemo 的语法是:

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
Enter fullscreen mode Exit fullscreen mode

如您所见,useMemo 接受两个参数:

  • 返回一个值以便记忆的函数。
  • 确定何时应重新计算记忆值的依赖项数组。

以下是 useMemo 的一个例子:

    import React, { useState, useMemo } from 'react';

    const ExpensiveComponent = ({ a, b }) => {
      const computeExpensiveValue = (a, b) => {
        console.log('Computing expensive value...');
        return a + b;
      };

      const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

      return (
        <div>
          <p>Computed Value: {memoizedValue}</p>
        </div>
      );
    };

    const ParentComponent = () => {
      const [a, setA] = useState(1);
      const [b, setB] = useState(2);
      const [count, setCount] = useState(0);

      return (
        <div>
          <ExpensiveComponent a={a} b={b} />
          <button onClick={() => setCount(count + 1)}>Increment Count</button>
        </div>
      );
    };
Enter fullscreen mode Exit fullscreen mode

3. 代码拆分

在传统设置中,应用程序的所有组件都捆绑在一个文件中。代码拆分是一种优化技术,用于将应用程序分解成更小的块。它可以减少应用程序的加载时间,因为您可以加载较小的组件,并避免加载其他不需要的组件。

以下是代码拆分的一个例子:

    import React, { useState } from 'react';

    function App() {
      const [component, setComponent] = useState(null);

      const loadComponent = async () => {
        const { default: LoadedComponent } = await import('./MyComponent');
        setComponent(<LoadedComponent />);
      };

      return (
        <div>
          <h1>Code Splitting Example</h1>
          <button onClick={loadComponent}>Load Component</button>
          {component}
        </div>
      );
    }

    export default App;
Enter fullscreen mode Exit fullscreen mode

4. React 延迟加载

React.Lazy 是优化组件加载的重要方法。它支持延迟加载组件。这意味着该组件仅在需要时加载。使用此功能,您可以将应用程序拆分成更小的组件,并按需加载。

React.lazy()用于动态导入组件。当需要该组件时,它会被异步加载,在此之前,可以显示一个后备 UI(例如加载中的旋转图标)。

以下是延迟加载的一个例子:

    import React, { Suspense } from 'react';

    const LazyComponent = React.lazy(() => import('./MyComponent'));

    const App = () => {
      return (
        <div>
          <h1>My App</h1>
          <Suspense fallback={<div>Loading...</div>}>
            <LazyComponent />
          </Suspense>
        </div>
      );
    };

    export default App;
Enter fullscreen mode Exit fullscreen mode

节流和去抖

它不仅适用于 React,也适用于调用函数的通用编程。节流是一种定义函数执行频率的技术。当一个函数被节流时,无论事件触发多少次,它都只允许在指定的时间间隔内执行一次。例如,为按钮点击添加节流,这样按钮就不会被调用得太频繁。

节流示例:

    import React, { useState } from 'react';

    function ThrottledButton() {
      const [count, setCount] = useState(0);

      const throttle = (func, delay) => {
        let lastCall = 0;
        return () => {
          const now = new Date().getTime();
          if (now - lastCall >= delay) {
            lastCall = now;
            func();
          }
        };
      };

      const incrementCount = () => {
        setCount((prevCount) => prevCount + 1);
      };

      const throttledIncrement = throttle(incrementCount, 2000);

      return (
        <div>
          <h1>Count: {count}</h1>
          <button onClick={throttledIncrement}>Click Me</button>
        </div>
      );
    }

    export default ThrottledButton;
Enter fullscreen mode Exit fullscreen mode

去抖动 (Debounce) 用于确保函数在调用后经过一段时间后执行。当某个事件重复发生时,去抖动函数仅在该事件停止触发指定的延迟时间后执行。例如,当用户输入搜索输入并提供建议时,我们会等待几毫秒后再调用该函数,以便用户完成输入。

去抖动示例:

    import React, { useState } from 'react';

    function debounce(func, delay) {
      let timeoutId;
      return function (...args) {
        if (timeoutId) {
          clearTimeout(timeoutId);
        }
        timeoutId = setTimeout(() => {
          func(...args);
        }, delay);
      };
    }

    const DebouncedSearch = () => {
      const [query, setQuery] = useState('');

      const handleSearch = (event) => {
        setQuery(event.target.value);
        console.log('Searching for:', event.target.value);
        // Here you would typically trigger an API call or filter a list based on the query
      };

      const debouncedSearch = debounce(handleSearch, 500);

      return (
        <div>
          <h1>Search</h1>
          <input
            type="text"
            placeholder="Type to search..."
            onChange={debouncedSearch}
          />
          <p>Search Query: {query}</p>
        </div>
      );
    };

    export default DebouncedSearch;
Enter fullscreen mode Exit fullscreen mode

与我联系

让我们保持联系,随时了解科技、创新及其他领域的最新资讯!🚀

此外,如果您有兴趣,我愿意撰写自由撰稿文章,请通过电子邮件或社交媒体与我联系。

结论

优化 React 应用程序对于确保其平稳高效运行至关重要,尤其是在其复杂性和规模不断增长的情况下。通过结合列表虚拟化、memoization useMemo、代码拆分、延迟加载、节流和去抖动等技术,您可以显著提升 React 应用程序的性能。

希望此方法能够帮助您优化 React 应用程序的性能。感谢您阅读本文。

文章来源:https://dev.to/surajondev/optimizing-react-applications-for-maximum-performance-5epm
PREV
我的职业故事 - 从训练营到谷歌,大约一年时间
NEXT
在 React 中构建无限滚动组件简介 App 组件无限滚动与我联系🚀 结论