LoginSignup
1
0

More than 1 year has passed since last update.

React18のSuspense機能を試してみる

Last updated at Posted at 2022-07-03

久々の投稿で小ネタを。

React18ではSuspense機能によりコンポーネントのレンダリングに中断が行えるようになりました。
それにより、コンポーネント自体を非同期でレンダリングできるようになりました。

実際に使ってみました。

成果物

Jul-03-2022 20-14-22.gif

ソースコード:https://codesandbox.io/embed/react-suspense-sample-jw80ks?fontsize=14&hidenavigation=1&theme=dark

読み込み中はスピンスピンをスピンさせています🌀
非同期用のコンポーネントにはダミーのJSONのAPIを叩くコンポーネントを用意しました。

App.js
import "./styles.css";
import React from 'react';
import Spinner from './Components/Spinner';
const OtherComponent = React.lazy(() => import('./Components/OtherComponent'));

export default function App() {
  return (
    <React.Suspense fallback={<Spinner />}>
      <div>
        <OtherComponent />
      </div>
    </React.Suspense>
  );
}

React.Suspenseコンポーネントを呼び出しています。
fallbackはロード中に表示させるコンポーネントです。

React.Suspenseコンポーネントタグの中にを呼び出しており、はダミーのJSONのAPIを叩くコンポーネントです。

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

といった形でReact.lazyで読み込んでいます。

ダミーのJSONのAPIを叩くコンポーネントの中身

OtherComponent.jsx
import useSWR from "swr";
const fetcher = () =>
  fetch("https://dummyjson.com/products/1").then((res) => res.json());

const OtherComponent = () => {
  const { data } = useSWR("https://dummyjson.com/products/1", fetcher);

  return (
    <div>
      <h1>useSWRを使ったコンポーネントResult</h1>
      <ul>
        {data &&
          Object.entries(data).map(([key, val], index) => {
            return (
              <li key={index}>
                {key}: {val}
              </li>
            );
          })}
      </ul>
    </div>
  );
};

export default OtherComponent;

先の React.Suspense の中身に対して useSWR をかませてデータをフェッチしてあげることで非同期でコンポーネントの読み込みが実現できます。

コンポーネントをフォールバックと切り離せ、従来なら必要だった同一コンポーネント内での条件分岐的なJSXも記述しなくて良いのでスッキリ書けました。

1
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
1
0