patternjavascriptreactModeratepending
React Suspense and lazy loading patterns
Viewed 0 times
lazy loadingcode splittingsuspensedynamic importbundle size
Problem
Need to split large React applications into smaller bundles that load on demand.
Solution
Use React.lazy and Suspense for route-level code splitting:
import { Suspense, lazy } from 'react';
// Lazy-load route components
const Dashboard = lazy(() => import('./pages/Dashboard'));
const Settings = lazy(() => import('./pages/Settings'));
const Profile = lazy(() => import('./pages/Profile'));
// Loading fallback
function LoadingSpinner() {
return <div className="spinner">Loading...</div>;
}
// App with lazy routes
function App() {
return (
<Suspense fallback={<LoadingSpinner />}>
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path="/settings" element={<Settings />} />
<Route path="/profile" element={<Profile />} />
</Routes>
</Suspense>
);
}
// Prefetch on hover (preload before user clicks)
function NavLink({ to, children }) {
const prefetch = () => {
// Triggers the dynamic import early
if (to === '/settings') import('./pages/Settings');
if (to === '/profile') import('./pages/Profile');
};
return (
<Link to={to} onMouseEnter={prefetch}>
{children}
</Link>
);
}
// Named exports need a wrapper
const MyComponent = lazy(() =>
import('./MyComponent').then(mod => ({ default: mod.MyComponent }))
);Why
Code splitting reduces initial bundle size. Users only download code for the features they actually use.
Gotchas
- lazy() only works with default exports (or use wrapper)
- Suspense boundary catches ALL lazy children - place strategically
- SSR requires additional handling (use Next.js dynamic imports)
Context
Large React applications needing faster initial load
Revisions (0)
No revisions yet.