Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Next.jsにおけるLazy Loading

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
Avatar for imaimai17468 imaimai17468
July 16, 2024
640

Next.jsにおけるLazy Loading

Next.jsでのLazyLoadingを使用したローディングの実装方法について解説します。

Avatar for imaimai17468

imaimai17468

July 16, 2024
Tweet

More Decks by imaimai17468

Transcript

  1. Dynamic Imports next/dynamic 動的インポートをサポートするモジュール React.lazy( )と Suspense で実装 使用例 const

    DynamicComponent = dynamic(() => import("./DynamicComponent")); 名前付き export をしたコンポーネントは解決する必要アリ const DynamicComponent = dynamic(() => import("./components").then((mod) => mod.NamedExport) ); 5
  2. Dynamic Imports によるローディング ClientComponent の場合 - ssr: false をつける const

    DynamicComponent = dynamic(() => import("./DynamicComponent"), { ssr: false, }); ローディング(fallback)の設定 - loadingプロパティを追加 const DynamicComponent = dynamic(() => import('./DynamicComponent'), { ssr: false loading: () => <p>Loading...</p>, }); 6
  3. Dynamic Imports によるローディング React.lazy( ) + Suspense に変換するとこんな感じ import React,

    { Suspense } from 'react'; const LazyComponent = React.lazy(() => import('./LazyComponent')); export const App() { return ( <Suspense fallback={<div>Loading...</div>}> <LazyComponent /> </Suspense> ); } 7
  4. ServerComponentを定義 export const AsyncServerComponent = async () => { const

    data = await fetchData(); return (...); }; Suspense で挟むだけ ... return ( <Suspense fallback={<p>Loading...</p>}> <AsyncServerComponent /> </Suspense> ); 9