Performance & Patterns
React Code Splitting with lazy and Suspense
Code splitting breaks the bundle into chunks loaded on demand. React.lazy takes a dynamic import and returns a component; Suspense renders a fallback while its chunk downloads.
What is Code Splitting with lazy and Suspense in React?
Code splitting breaks the bundle into chunks loaded on demand. React.lazy takes a dynamic import and returns a component; Suspense renders a fallback while its chunk downloads.
Code Splitting with lazy and Suspense example
import { lazy, Suspense } from 'react';
const SalaryChart = lazy(() => import('./SalaryChart'));
function Report() {
const [show, setShow] = useState(false);
return (
<>
<button onClick={() => setShow(true)}>Show salary chart</button>
{show && (
<Suspense fallback={<ChartSkeleton />}>
<SalaryChart />
</Suspense>
)}
</>
);
}How this works
The charting library is downloaded only when a user asks for the chart. Visitors who never click it never pay for those kilobytes.
Key points to remember
- The imported module must have a default export.
- Split at route boundaries first, then at heavy optional widgets.
- Wrap lazy components in an error boundary — a failed chunk load throws.
- Preload on hover with a manual import() call for a snappier feel.
Common mistakes with Code Splitting with lazy and Suspense
- Declaring lazy() inside a component, so a new lazy component is created each render.
- A fallback that is much smaller than the real content, causing layout shift.
React Code Splitting with lazy and Suspense— Interview Questions & FAQs
What happens if a lazy chunk fails to load?+
The import rejects and the component throws. Wrap it in an error boundary that offers a retry — this happens in the real world after a deploy invalidates old chunk filenames.
