Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
👋 Hi! I'm Dastan, author of Hack Frontend. Always open to professional networking => connect with me on LinkedIn.
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.
This is a function that allows dynamically importing component and returning it as regular React component.
const LazyComponent = React.lazy(() => import('./MyComponent'));
Since lazy component loading can take time, React offers Suspense component where you specify fallback — what to show while component loads.
import React, { Suspense } from "react";
const LazyComponent = React.lazy(() => import("./MyComponent"));
function App() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
</div>
);
}
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>
);
}
React Query, Relay, RSC, or Suspense for data (in future).Suspense.| 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 |
Tip:
Use React.lazy for lazy loading pages, modal windows, large blocks and other infrequently used components.