問題一覧に戻る
上級パフォーマンス最適化
問題86: コード分割戦略

初期バンドルサイズを削減するコード分割戦略を学びます。ルートベース分割はページをオンデマンドで読み込みます。機能ベース分割は重いコンポーネントを必要時に読み込みます。React.lazyとSuspenseが動的インポートを可能にします。これにより初期読み込み時間が改善され、機能の並列読み込みが可能になり、大規模アプリケーションに不可欠です。

import React, { lazy, Suspense } from 'react';

{/* ルートベースのコード分割 */}
const Home = (() => import('./pages/Home'));
const Profile = lazy(() => ('./pages/Profile'));

{/* 機能ベースの分割 */}
const Chart = lazy(() => import('./features/Chart'));

function App() {
const [page, setPage] = React.useState('home');
const [showChart, setShowChart] = React.useState(false);

return (
<div>
<nav>
<button onClick={() => setPage('home')}>Home</button>
<button onClick={() => setPage('profile')}>Profile</button>
</nav>

{/* ローディング用のSuspense */}
< fallback={<div>Loading...</div>}>
{page === 'home' && <Home />}
{page === 'profile' && < />}
</>

<button onClick={() => setShowChart(!showChart)}>
Toggle Chart
</button>

{showChart && (
{/* 機能の遅延読み込み */}
<Suspense fallback={<div></div>}>
<Chart />
</Suspense>
)}
</div>
);
}

export default App;