搜索
首页web前端js教程如何防止不必要的 React 组件重新渲染

How to Prevent Unnecessary React Component Re-Rendering

了解 React Native 如何渲染组件对于构建高效且高性能的应用程序至关重要。当组件的状态或属性发生变化时,React 会自动更新用户界面(UI)以反映这些变化。结果,React 再次调用组件的 render 方法来生成更新的 UI 表示。

在本文中,我们将探讨三个 React Hook 以及它们如何防止 React 中不必要的渲染

  • 使用备忘录
  • useCallback
  • useRef

这些工具使我们能够通过避免不必要的重新渲染、提高性能和有效存储值来优化代码。

在本文结束时,我们将更好地了解如何使用这些方便的 React hook 使我们的 React 应用程序更快、响应更快。

使用 React 的 useMemo

在 React 中,useMemo 可以防止不必要的重新渲染并优化性能。

让我们探索一下 useMemo 钩子如何防止 React 组件中不必要的重新渲染。

通过记住函数的结果并跟踪其依赖关系,useMemo 确保仅在必要时重新计算该过程。

考虑以下示例:

import { useMemo, useState } from 'react';

    function Page() {
      const [count, setCount] = useState(0);
      const [items] = useState(generateItems(300));

      const selectedItem = useMemo(() => items.find((item) => item.id === count), [
        count,
        items,
      ]);

      function generateItems(count) {
        const items = [];
        for (let i = 0; i 
          <h1 id="Count-count">Count: {count}</h1>
          <h1 id="Selected-Item-selectedItem-id">Selected Item: {selectedItem?.id}</h1>
          <button onclick="{()"> setCount(count + 1)}>Increment</button>
        
      );
    }

    export default Page;

上面的代码是一个名为Page的React组件,它使用useMemo来优化selectedItem计算。

解释如下:

  • 组件使用 useState 挂钩维护状态变量计数。
  • 项目状态是使用 useState 钩子和generateItems函数的结果来初始化的。
  • selectedItem是使用useMemo计算的,它会记住items.find操作的结果。仅当计数或项目发生变化时才会重新计算。
  • generateItems 函数根据给定的计数生成项目数组。
  • 该组件呈现当前 count 值、selectedItem id 以及用于增加计数的按钮。

使用 useMemo 通过记住 items.find 操作的结果来优化性能。它确保仅在依赖项(计数或项目)发生变化时才执行 selectedItem 的计算,从而防止后续渲染时不必要的重新计算。

应有选择地对计算密集型操作采用记忆化,因为它会给渲染过程带来额外的开销。

使用React的useCallback

React 中的 useCallback 钩子允许记忆函数,防止在每个组件渲染期间重新创建它们。通过利用 useCallback。只要其依赖项保持不变,部件仅创建一次并在后续渲染中重复使用。

考虑以下示例:

import React, { useState, useCallback, memo } from 'react';

    const allColors = ['red', 'green', 'blue', 'yellow', 'orange'];

    const shuffle = (array) => {
      const shuffledArray = [...array];
      for (let i = shuffledArray.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [shuffledArray[i], shuffledArray[j]] = [shuffledArray[j], shuffledArray[i]];
      }
      return shuffledArray;
    };

    const Filter = memo(({ onChange }) => {
      console.log('Filter rendered!');

      return (
        <input type="text" placeholder="Filter colors..." onchange="{(e)"> onChange(e.target.value)}
        />
      );
    });

    function Page() {
      const [colors, setColors] = useState(allColors);
      console.log(colors[0])

      const handleFilter = useCallback((text) => {
        const filteredColors = allColors.filter((color) =>
          color.includes(text.toLowerCase())
        );
        setColors(filteredColors);
      }, [colors]);


      return (
        <div classname="tutorial">
        <div classname="align-center mb-2 flex">
          <button onclick="{()"> setColors(shuffle(allColors))}>
            Shuffle
          </button>
          <filter onchange="{handleFilter}"></filter>
        </div>
        <ul>
          {colors.map((color) => (
            <li key="{color}">{color}</li>
          ))}
        </ul>
      </div>
      );
    }

    export default Page;

上面的代码演示了 React 组件中的简单颜色过滤和洗牌功能。让我们一步一步来:

  • 初始颜色数组定义为 allColors。
  • shuffle 函数接受一个数组并随机打乱其元素。它使用Fisher-Yates算法来实现洗牌。
  • Filter 组件是一个渲染输入元素的记忆化功能组件。它接收 onChange 属性并在输入值发生变化时触发回调函数。
  • Page 组件是渲染颜色过滤和洗牌功能的主要组件。
  • 状态变量颜色使用 useState 钩子进行初始化,初始值设置为 allColors。它代表过滤后的颜色列表。
  • handleFilter 函数是使用 useCallback 挂钩创建的。它采用文本参数并根据提供的文本过滤 allColors 数组。然后使用 useState 挂钩中的 setColors 函数设置过滤后的颜色。依赖数组 [colors] 确保仅在颜色状态发生变化时重新创建 handleFilter 函数,通过防止不必要的重新渲染来优化性能。
  • 页面组件内部有一个用于调整颜色的按钮。单击按钮时,它会使用经过排序的 allColors 数组调用 setColors 函数。
  • Filter 组件是通过将 onChange 属性设置为handleFilter 函数来渲染的。
  • 最后,颜色数组被映射以将颜色项列表渲染为
  • 元素。

useCallback 钩子用于记忆handleFilter 函数,这意味着该函数仅创建一次,并且如果依赖项(在本例中为颜色状态)保持不变,则在后续渲染中重用。

This optimization prevents unnecessary re-renders of child components that receive the handleFilter function as a prop, such as the Filter component.
It ensures that the Filter component is not re-rendered if the colors state hasn't changed, improving performance.

Using React's useRef

Another approach to enhance performance in React applications and avoid unnecessary re-renders is using the useRef hook. Using useRef, we can store a mutable value that persists across renders, effectively preventing unnecessary re-renders.

This technique allows us to maintain a reference to a value without triggering component updates when that value changes. By leveraging the mutability of the reference, we can optimize performance in specific scenarios.

Consider the following example:

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

function App() {
  const [name, setName] = useState('');
  const inputRef = useRef(null);

  function handleClick() {
    inputRef.current.focus();
  }

  return (
    <div>
      <input type="text" value="{name}" onchange="{(e)"> setName(e.target.value)}
        ref={inputRef}
      />
      <button onclick="{handleClick}">Focus</button>
    </div>
  );
}

The example above has a simple input field and a button. The useRef hook creates a ref called inputRef. As soon as the button is clicked, the handleClick function is called, which focuses on the input element by accessing the current property of the inputRef ref object. As such, it prevents unnecessary rerendering of the component when the input value changes.

To ensure optimal use of useRef, reserve it solely for mutable values that do not impact the component's rendering. If a mutable value influences the component's rendering, it should be stored within its state instead.

Conclusion

Throughout this tutorial, we explored the concept of React re-rendering and its potential impact on the performance of our applications. We delved into the optimization techniques that can help mitigate unnecessary re-renders. React offers a variety of hooks that enable us to enhance the performance of our applications. We can effectively store values and functions between renders by leveraging these hooks, significantly boosting React application performance.

以上是如何防止不必要的 React 组件重新渲染的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Java vs JavaScript:开发人员的详细比较Java vs JavaScript:开发人员的详细比较May 16, 2025 am 12:01 AM

javaandjavascriptaredistinctlanguages:javaisusedforenterpriseandmobileapps,while javascriptifforInteractiveWebpages.1)JavaisComcompoppored,statieldinglationallyTypted,statilly tater astrunsonjvm.2)

JavaScript数据类型:浏览器和nodejs之间是否有区别?JavaScript数据类型:浏览器和nodejs之间是否有区别?May 14, 2025 am 12:15 AM

JavaScript核心数据类型在浏览器和Node.js中一致,但处理方式和额外类型有所不同。1)全局对象在浏览器中为window,在Node.js中为global。2)Node.js独有Buffer对象,用于处理二进制数据。3)性能和时间处理在两者间也有差异,需根据环境调整代码。

JavaScript评论:使用//和 / * * / * / * /JavaScript评论:使用//和 / * * / * / * /May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript:开发人员的比较分析Python vs. JavaScript:开发人员的比较分析May 09, 2025 am 12:22 AM

Python和JavaScript的主要区别在于类型系统和应用场景。1.Python使用动态类型,适合科学计算和数据分析。2.JavaScript采用弱类型,广泛用于前端和全栈开发。两者在异步编程和性能优化上各有优势,选择时应根据项目需求决定。

Python vs. JavaScript:选择合适的工具Python vs. JavaScript:选择合适的工具May 08, 2025 am 12:10 AM

选择Python还是JavaScript取决于项目类型:1)数据科学和自动化任务选择Python;2)前端和全栈开发选择JavaScript。Python因其在数据处理和自动化方面的强大库而备受青睐,而JavaScript则因其在网页交互和全栈开发中的优势而不可或缺。

Python和JavaScript:了解每个的优势Python和JavaScript:了解每个的优势May 06, 2025 am 12:15 AM

Python和JavaScript各有优势,选择取决于项目需求和个人偏好。1.Python易学,语法简洁,适用于数据科学和后端开发,但执行速度较慢。2.JavaScript在前端开发中无处不在,异步编程能力强,Node.js使其适用于全栈开发,但语法可能复杂且易出错。

JavaScript的核心:它是在C还是C上构建的?JavaScript的核心:它是在C还是C上构建的?May 05, 2025 am 12:07 AM

javascriptisnotbuiltoncorc; saninterpretedlanguagethatrunsonenginesoftenwritteninc.1)javascriptwasdesignedAsalightweight,解释edganguageforwebbrowsers.2)Enginesevolvedfromsimpleterterterpretpreterterterpretertestojitcompilerers,典型地提示。

JavaScript应用程序:从前端到后端JavaScript应用程序:从前端到后端May 04, 2025 am 12:12 AM

JavaScript可用于前端和后端开发。前端通过DOM操作增强用户体验,后端通过Node.js处理服务器任务。1.前端示例:改变网页文本内容。2.后端示例:创建Node.js服务器。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

北端:融合系统,解释
1 个月前By尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆树的耳语 - 如何解锁抓钩
4 周前By尊渡假赌尊渡假赌尊渡假赌
<🎜>掩盖:探险33-如何获得完美的色度催化剂
2 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具