Code
react
import { lazy, Suspense, useState } from 'react';
// Lazy load component
const Dashboard = lazy(() => import('./Dashboard'));
const Settings = lazy(() => import('./Settings'));
const Profile = lazy(() => import('./Profile'));
function App() {
const [page, setPage] = useState('dashboard');
return (
<div>
<nav>
<button onClick={() => setPage('dashboard')}>Dashboard</button>
<button onClick={() => setPage('settings')}>Settings</button>
<button onClick={() => setPage('profile')}>Profile</button>
</nav>
<Suspense fallback={<div>Loading...</div>}>
{page === 'dashboard' && <Dashboard />}
{page === 'settings' && <Settings />}
{page === 'profile' && <Profile />}
</Suspense>
</div>
);
}
// Multiple components sharing Suspense
function App2() {
return (
<Suspense fallback={<Spinner />}>
<Header />
<Suspense fallback={<ContentLoader />}>
<MainContent />
</Suspense>
<Footer />
</Suspense>
);
}
// Preload
const lazyWithPreload = (factory) => {
const Component = lazy(factory);
Component.preload = factory;
return Component;
};
const HeavyChart = lazyWithPreload(() => import('./HeavyChart'));
// Preload on hover
<button onMouseEnter={() => HeavyChart.preload()}>
Show Chart
</button>