0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【React】遅延読み込みの際にsuspenseで表示されるコンポーネントを切り替える

Posted at

初めに

コンポーネントの読み込み中には、ロード中ということがユーザに伝わるような表示をさせておきたいです。
本記事ではReact の Suspense を使用し非同期にコンポーネントを読み込みを際に、読み込み前と後で表示コンポーネントを変える方法について記載します。

目次

1.環境
2.Suspenseの書き方
3.ソース
4.実行結果

環境

  • react:18.2
  • vite:5.2

Suspenseについて

Suspenseの書き方は次のようになります。
非同期処理の状態に応じて表示するコンポーネントを変える処理を記述する必要がなく、宣言的に書けるのは便利です。
詳細は下記リンクのドキュメントになります。

<Suspense fallback={<Loading />}>
  <SomeComponent />
</Suspense>
  • <Loading />:読み込みが完了するまで表示されるコンポーネント
  • <SomeComponent />:読み込み後に表示されるコンポーネント

ソース

以下が全体のソースになります。
setTimeoutで意図的に遅延を発生させ、非同期処理の完了前は「Loading...」の文字列、完了後には「3秒経ちました」の文字列を表示させています。

◆全体のソース

App.tsx
import React, { Suspense } from 'react';
import './App.css'

// 遅延
const fetchData = () => {
  return new Promise<string>(resolve => {
    setTimeout(() => resolve('3秒経ちました'), 3000);
  });
};

// 遅延されたデータを読み込むコンポーネント
const DataComponent = React.lazy(
  () => fetchData().then(
    (data) => ({ default: () => <div>{data}</div> }))
);

const App = () => {
  return (
    <div>
      <h1>Hello React Suspense!</h1>
      <Suspense fallback={<div>Loading...</div>}>
        <DataComponent />
      </Suspense>
    </div>
  );
};

export default App;

◆詳細

以下のfetchData関数においては、非同期の処理を行いsetTimeout が3秒後にコールバック関数を実行するように設定しています。

const fetchData = () => {
  return new Promise<string>(resolve => {
    setTimeout(() => resolve('3秒経ちました'), 3000);
  });
};

以下のDataComponentコンポーネントでは、React.lazyを使用しコンポーネントの遅延読み込みを行っています。
fetchData関数の非同期処理完了後に、コンポーネントを定義しています。

const DataComponent = React.lazy(
    () => fetchData().then((data) => ({ default: () => <div>{data}</div> }))
);

Suspensefallbackプロパティには、読み込みが終わるまで表示されるコンポーネントを指定しておきます。
非同期処理が終わりコンポーネントが読み込まれるとDataComponent が表示されます。

const App = () => {
  return (
    <div>
      <h1>Hello React Suspense!</h1>
      <Suspense fallback={<div>Loading...</div>}>
        <DataComponent />
      </Suspense>
    </div>
  );
};

実行結果

npm run devで実際に画面上の動作を確認してみます。
レンダリング時は「Loading...」の文言、その後に「3秒経ちました」の文言に代わっている事が確認できます。

react_suspense_m.gif

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?