搜索
首页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
在JavaScript中替换字符串字符在JavaScript中替换字符串字符Mar 11, 2025 am 12:07 AM

JavaScript字符串替换方法详解及常见问题解答 本文将探讨两种在JavaScript中替换字符串字符的方法:在JavaScript代码内部替换和在网页HTML内部替换。 在JavaScript代码内部替换字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 该方法仅替换第一个匹配项。要替换所有匹配项,需使用正则表达式并添加全局标志g: str = str.replace(/fi

jQuery检查日期是否有效jQuery检查日期是否有效Mar 01, 2025 am 08:51 AM

简单JavaScript函数用于检查日期是否有效。 function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //测试 var

jQuery获取元素填充/保证金jQuery获取元素填充/保证金Mar 01, 2025 am 08:53 AM

本文探讨如何使用 jQuery 获取和设置 DOM 元素的内边距和外边距值,特别是元素外边距和内边距的具体位置。虽然可以使用 CSS 设置元素的内边距和外边距,但获取准确的值可能会比较棘手。 // 设置 $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); 你可能会认为这段代码很

10个jQuery手风琴选项卡10个jQuery手风琴选项卡Mar 01, 2025 am 01:34 AM

本文探讨了十个特殊的jQuery选项卡和手风琴。 选项卡和手风琴之间的关键区别在于其内容面板的显示和隐藏方式。让我们深入研究这十个示例。 相关文章:10个jQuery选项卡插件

10值得检查jQuery插件10值得检查jQuery插件Mar 01, 2025 am 01:29 AM

发现十个杰出的jQuery插件,以提升您的网站的活力和视觉吸引力!这个精选的收藏品提供了不同的功能,从图像动画到交互式画廊。让我们探索这些强大的工具: 相关文章: 1

HTTP与节点和HTTP-Console调试HTTP与节点和HTTP-Console调试Mar 01, 2025 am 01:37 AM

HTTP-Console是一个节点模块,可为您提供用于执行HTTP命令的命令行接口。不管您是否针对Web服务器,Web Serv

自定义Google搜索API设置教程自定义Google搜索API设置教程Mar 04, 2025 am 01:06 AM

本教程向您展示了如何将自定义的Google搜索API集成到您的博客或网站中,提供了比标准WordPress主题搜索功能更精致的搜索体验。 令人惊讶的是简单!您将能够将搜索限制为Y

jQuery添加卷轴到DivjQuery添加卷轴到DivMar 01, 2025 am 01:30 AM

当div内容超出容器元素区域时,以下jQuery代码片段可用于添加滚动条。 (无演示,请直接复制到Firebug中) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c

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脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前By尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
4 周前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

PhpStorm Mac 版本

PhpStorm Mac 版本

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

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。