首頁 > web前端 > js教程 > 主體

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

WBOY
發布: 2024-09-10 11:09:24
原創
526 人瀏覽過

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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!