React.lazy and Suspense — Lazy Components in React
React.lazy and Suspense are tools in React that allow lazy loading components, meaning only when they're actually needed. This is called code splitting, and it helps improve application performance.
Why Is This Needed?
- Reduces first load time of application
- Splits code into separate chunks
- Loads heavy components as needed
- Especially important for SPA and mobile users
React.lazy
This is a function that allows dynamically importing component and returning it as regular React component.
Syntax:
const LazyComponent = React.lazy(() => import('./MyComponent'));
What is Suspense?
Since lazy component loading can take time, React offers Suspense component where you specify fallback — what to show while component loads.
Suspense Example
import React, { Suspense } from "react";
const LazyComponent = React.lazy(() => import("./MyComponent"));
function App() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
</div>
);
}
Routing Example
import { BrowserRouter, Routes, Route } from "react-router-dom";
import React, { lazy, Suspense } from "react";
const Home = lazy(() => import("./pages/Home"));
const About = lazy(() => import("./pages/About"));
function App() {
return (
<BrowserRouter>
<Suspense fallback={<p>Loading page...</p>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Suspense>
</BrowserRouter>
);
}
Important to Know
- Works only for default components. For other cases (functions, modules) — use import() directly.
- Suspense doesn't yet support data (e.g., API loading) — for this use
React Query,Relay,RSC, orSuspense for data(in future). - Can wrap multiple components in one
Suspense.
Performance Benefit
| Without lazy | With lazy | |
|---|---|---|
| Code loading | Entire bundle loads | Only needed parts load |
| Start speed | Long loading | Fast start |
| Optimization | Lots of unused code | Only necessary code |
Summary
- React.lazy allows loading components on demand
- Suspense needed to display placeholder during loading
- This helps make applications faster and more efficient
Tip:
Use React.lazy for lazy loading pages, modal windows, large blocks and other infrequently used components.