LoginSignup
0
0

【React】コンポーネントを動的にロードする

Posted at

React.lazy()を使用してコンポーネントを動的にロードする

React.lazy()は、React 16.6.0で導入された機能で、コンポーネントを動的にロードするための便利な方法を提供しています。これにより、アプリケーションの初期ロード時間を最適化し、必要なときに必要なコンポーネントだけをロードできます。

1. React.lazy()とは?

React.lazy()は、動的なインポートをサポートする関数で、遅延読み込みが可能なコンポーネントを生成します。通常、コンポーネントはimportステートメントを使用して直接読み込まれますが、React.lazy()を使用すると、そのコンポーネントはコード分割(code-splitting)が適用され、必要に応じて非同期的にロードされます。

const MyComponent = React.lazy(() => import('./MyComponent'));

2. React.lazy()の基本的な使用法

以下は、React.lazy()の基本的な使用法です。

components/MyComponent.jsx
import React from "react";

const MyComponent = () => {
  return <div>Hello, React!</div>;
};

export default MyComponent;
App.js
import "./App.css";
import React, { lazy, Suspense } from "react";

const MyComponent = lazy(() => import("./components/MyComponent"));

const App = () => {
  return (
    <div className="App">
      <Suspense fallback={<div>Loading...</div>}>
        <MyComponent />
      </Suspense>
    </div>
  );
};

export default App;

上記の例では、MyComponentReact.lazy()を使用して動的にロードされています。Suspenseコンポーネントは、遅延読み込み中に表示されるローディングメッセージを指定します。

3. Suspenseを使用したエラーハンドリング

Suspenseは非同期コンポーネントの読み込み中のローディングをハンドリングするだけでなく、エラーハンドリングにも使用できます。非同期コンポーネントのロード中にエラーが発生した場合、Suspensefallbackプロパティに指定されたローディングメッセージではなく、<ErrorBoundary>といったエラーコンポーネントを表示します。

App.js
import "./App.css";
import React, { lazy, Suspense } from "react";

const MyComponent = lazy(() => import("./components/MyComponent"));

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(_) {
    return { hasError: true };
  }

  render() {
    if (this.state.hasError) {
      return this.props.fallback;
    }

    return this.props.children;
  }
}

const App = () => {
  return (
    <div className="App">
      <Suspense fallback={<div>Loading...</div>}>
        <ErrorBoundary fallback={<h2>Error!!!!</h2>}>
          <MyComponent />
        </ErrorBoundary>
      </Suspense>
    </div>
  );
};

export default App;

4. まとめ

React.lazy()を使用することで、アプリケーションの初期ロード時間を最適化し、必要なときに必要なコンポーネントだけを非同期的にロードすることができます。Suspenseを使用してローディングとエラーハンドリングを簡単に組み込むことができます

この記事では、初心者大学生がReact Nextを理解するためのアウトプット資料です。
間違いや意見などコメントお待ちしております!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0