搜尋
首頁web前端js教程優化 React 應用程式以獲得更好效能的基本技術

Essential Techniques to Optimize React Applications for Better Performance

介紹

隨著現代 Web 應用程式變得越來越複雜,確保最佳效能變得越來越重要。 React 是一個用於建立使用者介面的流行 JavaScript 程式庫,它提供了各種策略來增強應用程式效能。無論您正在開發小型專案還是大型應用程序,了解並實施這些優化技術都可以帶來更快的載入時間、更流暢的使用者體驗和更有效率的資源使用。

在這篇文章中,我們將探索優化 React 應用程式的基本技術,從高效的狀態管理和最小化重新渲染到利用程式碼分割和延遲載入。這些策略不僅有助於交付高效能應用程序,而且還有助於隨著應用程式的成長保持可擴展性和響應能力。讓我們深入探討如何透過優化 React 應用程式的效能來充分利用它們。

1.使用React.memo:防止不必要的重新渲染

React.memo 是一個高階元件,可以幫助防止功能元件不必要的重新渲染。它的工作原理是記住元件的渲染輸出,並且僅在其 props 發生變化時重新渲染它。這可以帶來顯著的效能提升,特別是對於頻繁渲染但其 props 不經常更改的元件。

例子

讓我們來看一個使用 React.memo 來避免不必要的重新渲染的範例:

import React, { useState } from 'react';

// A functional component that displays a count
const CountDisplay = React.memo(({ count }) => {
  console.log('CountDisplay rendered');
  return <div>Count: {count}</div>;
});

const App = () => {
  const [count, setCount] = useState(0);
  const [text, setText] = useState('');

  return (
    <div>
      <button onclick="{()"> setCount(count + 1)}>Increment Count</button>
      <countdisplay count="{count}"></countdisplay>

      <input type="text" value="{text}" onchange="{(e)"> setText(e.target.value)}
        placeholder="Type something"
      />
    </div>
  );
};

export default App;
解釋
  • 當您按一下「遞增計數」按鈕時,CountDisplay 元件將會重新渲染,因為其 count 屬性會變更。
  • 當您在輸入欄位中鍵入內容時,CountDisplay 元件不會重新渲染,因為即使父 App 元件重新渲染,其 count 屬性仍保持不變。
2.使用useMemo和useCallback Hooks:Memoize昂貴的計算

React 的 useMemo 和 useCallback 鉤子用於記憶昂貴的計算和函數,防止不必要的重新計算和重新渲染。這些鉤子可以顯著提高 React 應用程式的效能,尤其是在處理複雜計算或頻繁渲染的元件時。

使用備忘錄

useMemo 用於記憶值,因此僅當其依賴項之一發生變更時才會重新計算。

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

const ExpensiveCalculationComponent = ({ num }) => {
  const expensiveCalculation = (n) => {
    console.log('Calculating...');
    return n * 2; // Simulate an expensive calculation
  };

  const result = useMemo(() => expensiveCalculation(num), [num]);

  return <div>Result: {result}</div>;
};

const App = () => {
  const [num, setNum] = useState(1);
  const [text, setText] = useState('');

  return (
    <div>
      <button onclick="{()"> setNum(num + 1)}>Increment Number</button>
      <expensivecalculationcomponent num="{num}"></expensivecalculationcomponent>

      <input type="text" value="{text}" onchange="{(e)"> setText(e.target.value)}
        placeholder="Type something"
      />
    </div>
  );
};

export default App;
解釋
  • 點擊「遞增數字」按鈕會觸發昂貴的計算,您將在控制台中看到「正在計算...」。
  • 由於 useMemo,在輸入欄位中鍵入內容不會觸發昂貴的計算。
使用回調

useCallback 用於記憶函數,因此僅當其依賴項之一發生變更時才會重新建立它。

例子
import React, { useState, useCallback } from 'react';

const Button = React.memo(({ handleClick, label }) => {
  console.log(`Rendering button - ${label}`);
  return <button onclick="{handleClick}">{label}</button>;
});

const App = () => {
  const [count, setCount] = useState(0);
  const [text, setText] = useState('');

  const increment = useCallback(() => {
    setCount((prevCount) => prevCount + 1);
  }, []);

  return (
    <div>
      <button handleclick="{increment}" label="Increment Count"></button>
      <div>Count: {count}</div>

      <input type="text" value="{text}" onchange="{(e)"> setText(e.target.value)}
        placeholder="Type something"
      />
    </div>
  );
};

export default App;
說明
  • 點選「遞增計數」按鈕會觸發遞增功能,且 Button 元件不會不必要地重新渲染。
  • 由於 useCallback,在輸入欄位中鍵入內容不會導致 Button 元件重新渲染。
3. 延遲載入和程式碼分割:動態載入元件

延遲載入和程式碼分割是 React 中使用的技術,透過僅在需要時載入元件來提高應用程式的效能。這可以減少初始載入時間並改善整體用戶體驗。

- 使用 React.lazy 和 Suspense 進行延遲加載

React 提供了一個內建函數 React.lazy 來實現元件的延遲載入。它允許您將程式碼分割成更小的區塊並按需載入它們。

例子
import React, { Suspense } from 'react';

// Lazy load the component
const MyLazyComponent = React.lazy(() => import('./MayLazyComponent'));

const App = () => {
  return (
    <div>
      <h1 id="Welcome-to-My-App">Welcome to My App</h1>

      {/* Suspense component wraps the lazy loaded component */}
      <suspense fallback="{<div">Loading...</suspense>
</div>}>
        <mylazycomponent></mylazycomponent>
      
    
  );
};

export default App;
解釋
1.React.lazy:
  • React.lazy 用於動態導入 LazyComponent。
  • 導入語句傳回一個解析為元件的承諾。
2、懸念:
  • Suspense 組件用於包裝延遲加載組件。
  • 它提供了一個後備 UI(正在載入...)以在載入元件時顯示。
- 使用 React.lazy 和 React Router 進行程式碼分割

您也可以使用 React Router 的延遲載入和程式碼分割來動態載入路由元件。

例子
import React, { Suspense } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

// Lazy load the components
const Home = React.lazy(() => import('./Home'));
const About = React.lazy(() => import('./About'));

const App = () => {
  return (
    <router>
      <div>
        <h1 id="My-App-with-React-Router">My App with React Router</h1>

        <suspense fallback="{<div">Loading...</suspense>
</div>}>
          <routes>
            <route path="/" element="{<Home"></route>} />
            <route path="/about" element="{<About"></route>} />
          </routes>
        
      
    </router>
  );
};

export default App;
解釋
  • 延遲載入路由元件:
    React.lazy 用於動態匯入 Home 和 About 元件。

  • 懸念與反應路由器:
    Suspense 元件包裝了 Routes 元件,以便在載入路由元件時提供後備 UI。

4. Virtualize Long Lists: Renders only the visible items

Virtualizing long lists in React using libraries like react-window or react-virtualized can significantly improve performance by rendering only the visible items. This technique is essential for handling large datasets efficiently and ensuring a smooth user experience.

Example
import React from 'react';
import { List } from 'react-virtualized';

const rowRenderer = ({ index, key, style }) => (
  <div key="{key}" style="{style}">
    Row {index}
  </div>
);

const App = () => {
  return (
    <list width="{300}" height="{400}" rowcount="{1000}" rowheight="{35}" rowrenderer="{rowRenderer}"></list>
  );
};

export default App;
5. Debounce & Throttle Events: Limits the frequency of expensive operations

Debouncing and throttling are essential techniques to optimize performance in React applications by controlling the frequency of expensive operations. Debouncing is ideal for events like key presses, while throttling is more suited for continuous events like scrolling or resizing. Using utility libraries like Lodash can simplify the implementation of these techniques.

- Debounce

Debouncing ensures that a function is only executed once after a specified delay has passed since the last time it was invoked. This is particularly useful for events that trigger frequently, such as key presses in a search input field.

Example using Lodash
import React, { useState, useCallback } from 'react';
import debounce from 'lodash/debounce';

const App = () => {
  const [value, setValue] = useState('');

  const handleInputChange = (event) => {
    setValue(event.target.value);
    debouncedSearch(event.target.value);
  };

  const search = (query) => {
    console.log('Searching for:', query);
    // Perform the search operation
  };

  const debouncedSearch = useCallback(debounce(search, 300), []);

  return (
    <div>
      <input type="text" value="{value}" onchange="{handleInputChange}">
    </div>
  );
};

export default App;
- Throttle

Throttling ensures that a function is executed at most once in a specified interval of time. This is useful for events like scrolling or resizing where you want to limit the rate at which the event handler executes.

Example using Lodash
import React, { useEffect } from 'react';
import throttle from 'lodash/throttle';

const App = () => {
  useEffect(() => {
    const handleScroll = throttle(() => {
      console.log('Scrolling...');
      // Perform scroll operation
    }, 200);

    window.addEventListener('scroll', handleScroll);

    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  return (
    <div style="{{" height:>
      Scroll down to see the effect
    </div>
  );
};

export default App;
6. Optimize Images and Assets: Reduces the load time

Optimizing images and assets involves compressing files, using modern formats, serving responsive images, and implementing lazy loading. By following these techniques, you can significantly reduce load times and improve the performance of your React application.

Use the loading attribute for images to enable native lazy loading or use a React library like react-lazyload.

Example
import React from 'react';
import lazyImage from './lazy-image.webp';

const LazyImage = () => {
  return (
    <div>
      <img src="%7BlazyImage%7D" alt="Lazy Loaded" loading="lazy" native lazy   style="max-width:90%" width: maxwidth:>
    </div>
  );
};

export default LazyImage;
7. Avoid Inline Functions and Object Literals:

Avoiding inline functions and object literals is important for optimizing performance in React applications. By using useCallback to memoize functions and defining objects outside of the render method, you can minimize unnecessary re-renders and improve the efficiency of your components.

Example
// 1. Inline Function

// Problematic Code:
 <button onclick="{()"> setCount(count + 1)}>Increment</button>

// Optimized Code:
  // Use useCallback to memoize the function
  const handleClick = useCallback(() => {
    setCount((prevCount) => prevCount + 1);
  }, []);

 <button onclick="{handleClick}">Increment</button>

// 2. Inline Object Literals

// Problematic Code:
    <div style="{{" padding: backgroundcolor:>
      <p>Age: {age}</p>
    </div>

// Optimized Code:
    const styles = {
         container: {
             padding: '20px',
             backgroundColor: '#f0f0f0',
        },
    };

    <div style="{styles.container}">
      <p>Age: {age}</p>
    </div>
8. Key Attribute in Lists: React identify which items have changed

When rendering lists in React, using the key attribute is crucial for optimal rendering and performance. It helps React identify which items have changed, been added, or removed, allowing for efficient updates to the user interface.

Example without key attribute

In this example, the key attribute is missing from the list items. React will not be able to efficiently track changes in the list, which could lead to performance issues and incorrect rendering.

    
    {items.map((item) => (
  • {item}
  • ))}
Example with key attribute as index

In the optimized code, the key attribute is added to each

  • element. The key value should be a unique identifier for each item. In this case, the index of the item is used as the key. However, it's recommended to use a unique identifier (e.g., item.id) if available, as using indices can cause issues if the list items are reordered or changed.
       
      {items.map((item, index) => (
    • {item}
    • ))}
    Example with Unique Identifiers:

    In this example, each list item has a unique id which is used as the key. This approach provides a more reliable way to track items and handle list changes, especially when items are dynamically added, removed, or reordered.

        
      {items.map((item) => (
    • {item.name}
    • ))}
    9. Use Production Build:

    Always use the production build for your React app to benefit from optimizations like minification and dead code elimination.

    Build Command: npm run build
    10. Profile and Monitor Performance:

    Profiling and monitoring performance are crucial for ensuring that your React application runs smoothly and efficiently. This involves identifying and addressing performance bottlenecks, ensuring that your application is responsive and performs well under various conditions.

    - Use React Developer Tools

    React Developer Tools is a browser extension that provides powerful tools for profiling and monitoring your React application. It allows you to inspect component hierarchies, analyze component renders, and measure performance.

    - Analyze Performance Metrics

    Use the performance metrics provided by React Developer Tools to identify slow components and unnecessary re-renders. Look for:

    • 渲染時間:每個元件渲染需要多長時間。
    • 元件更新:元件重新渲染的頻率。
    • 互動:使用者互動對效能的影響

    最後的想法

    實作這些最佳化技術可以大幅增強 React 應用程式的效能,從而加快載入時間、更流暢的互動並全面改善使用者體驗。定期分析和監控,再加上這些技術的仔細應用,可確保您的 React 應用程式在成長時保持高效能和可擴展性。

  • 以上是優化 React 應用程式以獲得更好效能的基本技術的詳細內容。更多資訊請關注PHP中文網其他相關文章!

    陳述
    本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
    使用Next.js(後端集成)構建多租戶SaaS應用程序使用Next.js(後端集成)構建多租戶SaaS應用程序Apr 11, 2025 am 08:23 AM

    我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務

    如何使用Next.js(前端集成)構建多租戶SaaS應用程序如何使用Next.js(前端集成)構建多租戶SaaS應用程序Apr 11, 2025 am 08:22 AM

    本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫

    JavaScript:探索網絡語言的多功能性JavaScript:探索網絡語言的多功能性Apr 11, 2025 am 12:01 AM

    JavaScript是現代Web開發的核心語言,因其多樣性和靈活性而廣泛應用。 1)前端開發:通過DOM操作和現代框架(如React、Vue.js、Angular)構建動態網頁和單頁面應用。 2)服務器端開發:Node.js利用非阻塞I/O模型處理高並發和實時應用。 3)移動和桌面應用開發:通過ReactNative和Electron實現跨平台開發,提高開發效率。

    JavaScript的演變:當前的趨勢和未來前景JavaScript的演變:當前的趨勢和未來前景Apr 10, 2025 am 09:33 AM

    JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

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

    JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

    Python還是JavaScript更好?Python還是JavaScript更好?Apr 06, 2025 am 12:14 AM

    Python更适合数据科学和机器学习,JavaScript更适合前端和全栈开发。1.Python以简洁语法和丰富库生态著称,适用于数据分析和Web开发。2.JavaScript是前端开发核心,Node.js支持服务器端编程,适用于全栈开发。

    如何安裝JavaScript?如何安裝JavaScript?Apr 05, 2025 am 12:16 AM

    JavaScript不需要安裝,因為它已內置於現代瀏覽器中。你只需文本編輯器和瀏覽器即可開始使用。 1)在瀏覽器環境中,通過標籤嵌入HTML文件中運行。 2)在Node.js環境中,下載並安裝Node.js後,通過命令行運行JavaScript文件。

    在Quartz中如何在任務開始前發送通知?在Quartz中如何在任務開始前發送通知?Apr 04, 2025 pm 09:24 PM

    如何在Quartz中提前發送任務通知在使用Quartz定時器進行任務調度時,任務的執行時間是由cron表達式設定的。現�...

    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.能量晶體解釋及其做什麼(黃色晶體)
    3 週前By尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O.最佳圖形設置
    3 週前By尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O.如果您聽不到任何人,如何修復音頻
    3 週前By尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25:如何解鎖Myrise中的所有內容
    3 週前By尊渡假赌尊渡假赌尊渡假赌

    熱工具

    SecLists

    SecLists

    SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

    Dreamweaver Mac版

    Dreamweaver Mac版

    視覺化網頁開發工具

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

    VSCode Windows 64位元 下載

    VSCode Windows 64位元 下載

    微軟推出的免費、功能強大的一款IDE編輯器

    EditPlus 中文破解版

    EditPlus 中文破解版

    體積小,語法高亮,不支援程式碼提示功能