Lazy loading splits code into separate chunks that load only when needed, reducing the initial bundle size and speeding up the first load. Component-level lazy loading with React.lazy and Suspense import { lazy, Suspense } from 'react'; const ReportsPage = lazy(() => import('./pages/ReportsPage')); // must have a default export const Chart = lazy(() => import('./components/HeavyChart')); function Dashboard() { const [showChart, setShowChart] = useState(false); return ( <> <button onClick={() => setShowChart(true)}>Show chart</button> {showChart && ( <Suspense fallback={<p>Loading chart…</p>}> <Chart /> </Suspense> )} </> ); } Route-level lazy loading with React Router import { BrowserRouter, Routes, Route } from 'react-router-dom'; const Home = lazy(() => import('./pages/Home')); const Orders = lazy(() => import('./pages/Orders')); const Settings = lazy(() => import('./pages/Settings')); export function App() { return ( <BrowserRouter> <ErrorBoundary fallback={<p>Failed to load page. Please refresh.</p>}> <Suspense fallback={<div className="spinner" aria-label="Loading" />}> <Routes> <Route path="/" element={<Home />} /> <Route path="/orders" element={<Orders />} /> <Route path="/settings" element={<Settings />} /> </Routes> </Suspense> </ErrorBoundary> </BrowserRouter> ); } React Router's data routers also support a lazy property on route objects, which loads route modules (component, loader, action) on demand. Named exports lazy() expects a default export. For a named export: const Editor = lazy(() => import('./Editor').then(m => ({ default: m.Editor }))); Good practices - Split by route first (biggest wins), then heavy components: charts, rich text editors, maps, PDF viewers. - Wrap lazy components in an error boundary, because chunk loading can fail (network issues or a new deployment removing old chunks). Offer a reload. - Preload likely next pages on hover or when idle: const loadOrders = () => import('./pages/Orders'); call it in onMouseEnter of a link. - Avoid over-splitting into many tiny chunks, which adds request overhead. - Lazy-load images with loading="lazy" and below-the-fold content with IntersectionObserver. Vite and webpack create separate chunks automatically for each dynamic import().
Ravindra Wadile · · 0 likes