React アプリケーションの最適化

PHPz
リリース: 2024-09-08 20:30:31
オリジナル
439 人が閲覧しました

Optimize React Application

React アプリケーションを最適化するには、パフォーマンス、バンドル サイズの削減、効率的なレンダリング、全体的なユーザー エクスペリエンスに焦点を当てたいくつかの重要な戦略を使用できます。 React に特有の最適化テクニックの内訳は次のとおりです:

1. コード分割

コード分割を使用すると、アプリケーション全体を一度にロードするのではなく、必要に応じてロードできる小さなチャンクにアプリケーションを分割できます。これにより、初期ロード時間が短縮されます。

  • React.lazy: React の組み込み遅延読み込み機能を使用してコンポーネントを動的にインポートします。
  const LazyComponent = React.lazy(() => import('./Component'));

  function App() {
    return (
      <react.suspense fallback="{<div">Loading...}>
        <lazycomponent></lazycomponent>
      </react.suspense>
    );
  }
ログイン後にコピー
  • React Loadable: または、react-loadable のようなライブラリを使用して、より高度なコード分割オプションを使用することもできます。

2. メモ化と不必要な再レンダリングの防止

React アプリケーションのパフォーマンスを向上させるには、不必要な再レンダリングを回避することが重要です。

  • React.memo: 機能コンポーネントを React.memo でラップして、プロパティが変更されていない場合に再レンダリングされないようにします。
  const MyComponent = React.memo(({ value }) => {
    return <div>{value}</div>;
  });
ログイン後にコピー
  • useMemo: 高価な計算をメモ化し、必要な場合を除き、レンダリングのたびに計算が再計算されないようにします。
  const computedValue = useMemo(() => expensiveComputation(value), [value]);
ログイン後にコピー
  • useCallback: 特に子コンポーネントまたはエフェクトの依存関係として使用される場合に、毎回新しい参照を渡すことを避けるために関数をメモ化します。
  const handleClick = useCallback(() => {
    console.log('Clicked');
  }, []);
ログイン後にコピー

3. 効率的な状態管理を使用する

不必要なレンダリングを回避する方法で状態を処理すると、パフォーマンスが大幅に向上します。

  • useReducer: 複雑な状態ロジックの場合、状態変更をより詳細に制御するには、useState の代わりに useReducer を使用することを検討してください。
  const [state, dispatch] = useReducer(reducer, initialState);
ログイン後にコピー
  • コンポーネントの分割: 状態が変化したときに必要な部分だけが再レンダリングされるようにコンポーネントを分割します。

4. 長いリストを仮想化

長いリストやテーブルをレンダリングすると、パフォーマンスが低下する可能性があります。リスト仮想化技術を使用して、画面に表示されているもののみをレンダリングします。

  • react-window または react-virtualized: これらのライブラリを使用すると、リストを仮想化することで大規模なデータセットを効率的にレンダリングできます。
  import { FixedSizeList as List } from 'react-window';

  const MyList = ({ items }) => (
    <list height="{500}" itemcount="{items.length}" itemsize="{35}" width="{300}">
      {({ index, style }) => <div style="{style}">{items[index]}</div>}
    </list>
  );
ログイン後にコピー

5. 木が揺れる

アプリケーションがバンドル サイズを削減するために使用されているライブラリの部分のみをインポートするようにしてください。

  • ES6 imports: ライブラリ全体ではなく、ライブラリ (lodash、moment.js など) から必要なモジュールのみをインポートします。
  // Instead of this:
  import _ from 'lodash';

  // Do this:
  import debounce from 'lodash/debounce';
ログイン後にコピー

6. 画像の遅延読み込み

多くの場合、画像はページ上の最大の資産です。遅延読み込みを使用して、画像がビューポートに表示されるまで読み込みを遅らせます。

  • react-lazyload: 画像の単純な遅延読み込みには、react-lazyload ライブラリを使用します。
  import LazyLoad from 'react-lazyload';

  const ImageComponent = () => (
    <lazyload height="{200}" once>
      <img src="image-url.jpg" alt="React アプリケーションの最適化">
    </lazyload>
  );
ログイン後にコピー
  • Intersection Observer: Intersection Observer API を使用して、表示された画像を遅延して読み込むこともできます。
  const LazyImage = ({ src, alt }) => {
    const [inView, setInView] = useState(false);
    const imgRef = useRef(null);

    useEffect(() => {
      const observer = new IntersectionObserver(([entry]) => {
        if (entry.isIntersecting) {
          setInView(true);
          observer.disconnect();
        }
      });
      observer.observe(imgRef.current);
    }, []);

    return <img ref="{imgRef}" src="%7BinView" : alt="{alt}">;
  };
ログイン後にコピー

7. JavaScript を縮小します

  • Terser または Webpack の組み込み縮小化を使用して、ビルド プロセス中に JavaScript バンドルのサイズを削減します。

  • Create React App は、実稼働ビルド用のコードを自動的に縮小します:

  npm run build
ログイン後にコピー

8. バンドル分析

JavaScript バンドルのサイズを分析して、改善できる領域を特定します。

  • webpack-bundle-analyzer を使用してバンドルを視覚化し、どのライブラリが最も多くのスペースを占有しているかを確認します。
  npm install --save-dev webpack-bundle-analyzer
ログイン後にコピー

Webpack 構成内:

  const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
  module.exports = {
    plugins: [
      new BundleAnalyzerPlugin()
    ]
  };
ログイン後にコピー

9. 未使用の CSS を減らす

  • PurgeCSS などのツールを使用して、バンドルから未使用の CSS を削除します。これを Webpack または PostCSS 構成と統合できます。
  npm install @fullhuman/postcss-purgecss
ログイン後にコピー

PostCSS 構成の例:

  const purgecss = require('@fullhuman/postcss-purgecss')({
    content: ['./src/**/*.js', './public/index.html'],
    defaultExtractor: content => content.match(/[\w-/:]+(?



<h3>
  
  
  10. <strong>ネットワークリクエストを最適化する</strong>
</h3>

<p>ネットワーク リクエストの数を減らし、API 呼び出しを最適化すると、パフォーマンスが大幅に向上する可能性があります。</p>

ログイン後にコピー
  • Debouncing API Calls: Use debouncing to limit how often API requests are sent during user input.
  const fetchResults = debounce((query) => {
    // API call logic
  }, 300);
ログイン後にコピー
  • Caching API Data: Use libraries like SWR or React Query to cache API requests and avoid refetching data unnecessarily.
  import useSWR from 'swr';

  const fetcher = url => fetch(url).then(res => res.json());

  const MyComponent = () => {
    const { data, error } = useSWR('/api/data', fetcher);

    if (error) return <div>Error loading data</div>;
    if (!data) return <div>Loading...</div>;
    return <div>{data.message}</div>;
  };
ログイン後にコピー

11. Use React Fragments

Avoid adding unnecessary elements to the DOM by using React Fragments ( and >) when wrapping multiple elements.

const MyComponent = () => (
  
    <h1>Title</h1>
    <p>Content</p>
  >
);
ログイン後にコピー

12. Profiling and Performance Testing

Use the React Developer Tools profiler to identify performance bottlenecks in your app.

  • React Profiler: In Chrome or Firefox, open the React DevTools and switch to the "Profiler" tab. Record a session and analyze where components are re-rendering and consuming more time.

Conclusion

Optimizing a React application requires careful attention to performance, bundle size, and rendering efficiency. By employing techniques like code splitting, memoization, lazy loading, tree shaking, and minimizing network requests, you can significantly improve the performance of your app. Make sure to regularly analyze and test your app’s performance to catch any potential inefficiencies.

以上がReact アプリケーションの最適化の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!