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

如何防止不必要的 React 组件重新渲染

Sep 10, 2024 am 11:09 AM

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 < count; i++) {
          items.push({
            id: i,
            isSelected: i === count - 1,
          });
        }
        return items;
      }

      return (
        <div className="tutorial">
          <h1>Count: {count}</h1>
          <h1>Selected Item: {selectedItem?.id}</h1>
          <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
      );
    }

    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} />
        </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

热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

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

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

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

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

前端热敏纸小票打印遇到乱码问题怎么办? 前端热敏纸小票打印遇到乱码问题怎么办? Apr 04, 2025 pm 02:42 PM

前端热敏纸小票打印的常见问题与解决方案在前端开发中,小票打印是一个常见的需求。然而,很多开发者在实...

神秘的JavaScript:它的作用以及为什么重要 神秘的JavaScript:它的作用以及为什么重要 Apr 09, 2025 am 12:07 AM

JavaScript是现代Web开发的基石,它的主要功能包括事件驱动编程、动态内容生成和异步编程。1)事件驱动编程允许网页根据用户操作动态变化。2)动态内容生成使得页面内容可以根据条件调整。3)异步编程确保用户界面不被阻塞。JavaScript广泛应用于网页交互、单页面应用和服务器端开发,极大地提升了用户体验和跨平台开发的灵活性。

谁得到更多的Python或JavaScript? 谁得到更多的Python或JavaScript? Apr 04, 2025 am 12:09 AM

Python和JavaScript开发者的薪资没有绝对的高低,具体取决于技能和行业需求。1.Python在数据科学和机器学习领域可能薪资更高。2.JavaScript在前端和全栈开发中需求大,薪资也可观。3.影响因素包括经验、地理位置、公司规模和特定技能。

如何使用JavaScript将具有相同ID的数组元素合并到一个对象中? 如何使用JavaScript将具有相同ID的数组元素合并到一个对象中? Apr 04, 2025 pm 05:09 PM

如何在JavaScript中将具有相同ID的数组元素合并到一个对象中?在处理数据时,我们常常会遇到需要将具有相同ID�...

JavaScript难以学习吗? JavaScript难以学习吗? Apr 03, 2025 am 12:20 AM

学习JavaScript不难,但有挑战。1)理解基础概念如变量、数据类型、函数等。2)掌握异步编程,通过事件循环实现。3)使用DOM操作和Promise处理异步请求。4)避免常见错误,使用调试技巧。5)优化性能,遵循最佳实践。

如何实现视差滚动和元素动画效果,像资生堂官网那样?
或者:
怎样才能像资生堂官网一样,实现页面滚动伴随的动画效果? 如何实现视差滚动和元素动画效果,像资生堂官网那样? 或者: 怎样才能像资生堂官网一样,实现页面滚动伴随的动画效果? Apr 04, 2025 pm 05:36 PM

实现视差滚动和元素动画效果的探讨本文将探讨如何实现类似资生堂官网(https://www.shiseido.co.jp/sb/wonderland/)中�...

console.log输出结果差异:两次调用为何不同? console.log输出结果差异:两次调用为何不同? Apr 04, 2025 pm 05:12 PM

深入探讨console.log输出差异的根源本文将分析一段代码中console.log函数输出结果的差异,并解释其背后的原因。�...

JavaScript的演变:当前的趋势和未来前景 JavaScript的演变:当前的趋势和未来前景 Apr 10, 2025 am 09:33 AM

JavaScript的最新趋势包括TypeScript的崛起、现代框架和库的流行以及WebAssembly的应用。未来前景涵盖更强大的类型系统、服务器端JavaScript的发展、人工智能和机器学习的扩展以及物联网和边缘计算的潜力。

See all articles