導入
最新の Web アプリケーションが複雑になるにつれて、最適なパフォーマンスを確保することがますます重要になっています。ユーザー インターフェイスを構築するための人気のある JavaScript ライブラリである React は、アプリケーションのパフォーマンスを向上させるためのさまざまな戦略を提供します。小規模なプロジェクトに取り組んでいる場合でも、大規模なアプリケーションに取り組んでいる場合でも、これらの最適化手法を理解して実装すると、読み込み時間の短縮、ユーザー エクスペリエンスのスムーズ化、リソースの使用効率の向上につながります。
この投稿では、効率的な状態管理や再レンダリングの最小化から、コード分割や遅延読み込みの活用まで、React アプリケーションを最適化するための重要なテクニックを検討します。これらの戦略は、高パフォーマンスのアプリケーションを提供するだけでなく、アプリケーションの成長に応じたスケーラビリティと応答性を維持するのにも役立ちます。 React アプリケーションのパフォーマンスを最適化して、そのアプリケーションを最大限に活用する方法を詳しく見ていきましょう。
1. React.memo を使用する: 不必要な再レンダリングを防止します
React.memo は、機能コンポーネントの不必要な再レンダリングを防ぐのに役立つ高次コンポーネントです。これは、コンポーネントのレンダリングされた出力をメモ化し、プロパティが変更された場合にのみ再レンダリングすることで機能します。これにより、特に頻繁にレンダリングされるがプロパティが頻繁に変更されないコンポーネントの場合、パフォーマンスが大幅に向上する可能性があります。
例
不要な再レンダリングを避けるために 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 コンポーネントが再レンダリングされます。
- 入力フィールドに入力すると、親 App コンポーネントが再レンダリングされても、CountDisplay コンポーネントは再レンダリングされません。これは、Count プロパティが変更されないためです。
2. useMemo フックと useCallback フックを使用する: 高価な計算をメモ化する
React の useMemo フックと useCallback フックは、高価な計算と関数をメモ化し、不必要な再計算と再レンダリングを防ぐために使用されます。これらのフックは、特に複雑な計算や頻繁にレンダリングされるコンポーネントを処理する場合に、React アプリケーションのパフォーマンスを大幅に向上させることができます。
使用メモ
useMemo は値をメモ化するために使用されるため、依存関係の 1 つが変更された場合にのみ再計算されます。
例
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 のおかげで、入力フィールドに入力しても負荷の高い計算はトリガーされません。
useコールバック
useCallback は関数をメモ化するために使用されるため、依存関係の 1 つが変更された場合にのみ再作成されます。
例
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 を動的にインポートするために使用されます。
- import ステートメントは、コンポーネントに解決される Promise を返します。
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
-
{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 中国語 Web サイトの他の関連記事を参照してください。

現実世界でのJavaScriptのアプリケーションには、フロントエンドとバックエンドの開発が含まれます。 1)DOM操作とイベント処理を含むTODOリストアプリケーションを構築して、フロントエンドアプリケーションを表示します。 2)node.jsを介してRestfulapiを構築し、バックエンドアプリケーションをデモンストレーションします。

Web開発におけるJavaScriptの主な用途には、クライアントの相互作用、フォーム検証、非同期通信が含まれます。 1)DOM操作による動的なコンテンツの更新とユーザーインタラクション。 2)ユーザーエクスペリエンスを改善するためにデータを提出する前に、クライアントの検証が実行されます。 3)サーバーとのリフレッシュレス通信は、AJAXテクノロジーを通じて達成されます。

JavaScriptエンジンが内部的にどのように機能するかを理解することは、開発者にとってより効率的なコードの作成とパフォーマンスのボトルネックと最適化戦略の理解に役立つためです。 1)エンジンのワークフローには、3つの段階が含まれます。解析、コンパイル、実行。 2)実行プロセス中、エンジンはインラインキャッシュや非表示クラスなどの動的最適化を実行します。 3)ベストプラクティスには、グローバル変数の避け、ループの最適化、constとletsの使用、閉鎖の過度の使用の回避が含まれます。

Pythonは、スムーズな学習曲線と簡潔な構文を備えた初心者により適しています。 JavaScriptは、急な学習曲線と柔軟な構文を備えたフロントエンド開発に適しています。 1。Python構文は直感的で、データサイエンスやバックエンド開発に適しています。 2。JavaScriptは柔軟で、フロントエンドおよびサーバー側のプログラミングで広く使用されています。

PythonとJavaScriptには、コミュニティ、ライブラリ、リソースの観点から、独自の利点と短所があります。 1)Pythonコミュニティはフレンドリーで初心者に適していますが、フロントエンドの開発リソースはJavaScriptほど豊富ではありません。 2)Pythonはデータサイエンスおよび機械学習ライブラリで強力ですが、JavaScriptはフロントエンド開発ライブラリとフレームワークで優れています。 3)どちらも豊富な学習リソースを持っていますが、Pythonは公式文書から始めるのに適していますが、JavaScriptはMDNWebDocsにより優れています。選択は、プロジェクトのニーズと個人的な関心に基づいている必要があります。

C/CからJavaScriptへのシフトには、動的なタイピング、ゴミ収集、非同期プログラミングへの適応が必要です。 1)C/Cは、手動メモリ管理を必要とする静的に型付けられた言語であり、JavaScriptは動的に型付けされ、ごみ収集が自動的に処理されます。 2)C/Cはマシンコードにコンパイルする必要がありますが、JavaScriptは解釈言語です。 3)JavaScriptは、閉鎖、プロトタイプチェーン、約束などの概念を導入します。これにより、柔軟性と非同期プログラミング機能が向上します。

さまざまなJavaScriptエンジンは、各エンジンの実装原則と最適化戦略が異なるため、JavaScriptコードを解析および実行するときに異なる効果をもたらします。 1。語彙分析:ソースコードを語彙ユニットに変換します。 2。文法分析:抽象的な構文ツリーを生成します。 3。最適化とコンパイル:JITコンパイラを介してマシンコードを生成します。 4。実行:マシンコードを実行します。 V8エンジンはインスタントコンピレーションと非表示クラスを通じて最適化され、Spidermonkeyはタイプ推論システムを使用して、同じコードで異なるパフォーマンスパフォーマンスをもたらします。

現実世界におけるJavaScriptのアプリケーションには、サーバー側のプログラミング、モバイルアプリケーション開発、モノのインターネット制御が含まれます。 2。モバイルアプリケーションの開発は、ReactNativeを通じて実行され、クロスプラットフォームの展開をサポートします。 3.ハードウェアの相互作用に適したJohnny-Fiveライブラリを介したIoTデバイス制御に使用されます。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SecLists
SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。

PhpStorm Mac バージョン
最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール

AtomエディタMac版ダウンロード
最も人気のあるオープンソースエディター

ZendStudio 13.5.1 Mac
強力な PHP 統合開発環境
