Clean • Professional
As React applications grow, the bundle size can become large, making the app slow to load.
Lazy loading and code splitting help improve performance by loading components only when needed, instead of loading the entire application upfront.
Code splitting is a technique that splits your JavaScript bundle into smaller chunks.
Instead of sending all code at once, the browser loads only the code required for the current page or component.
Benefits:
Lazy loading is a way to load components only when they are rendered.
React provides a built-in function, React.lazy(), to implement lazy loading.
Syntax
const ComponentName = React.lazy(() => import('./ComponentName'));
React.lazy() takes a function that returns a dynamic import.Example: Lazy Loading a Component
import React, { Suspense } from "react";
const LazyComponent = React.lazy(() => import("./LazyComponent"));
function App() {
return (
<div>
<h1>React Lazy Loading Example</h1>
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
</div>
);
}
export default App;
Suspense is required to handle the loading state while the component is being fetched.fallback can be any JSX, such as a spinner or placeholder text.LazyComponent is not included in the initial bundle; it loads only when rendered.Lazy loading is especially useful with React Router, where different routes load different components.
import React, { Suspense } from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
const Home = React.lazy(() => import("./Home"));
const About = React.lazy(() => import("./About"));
function App() {
return (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Suspense>
</Router>
);
}
export default App;
Benefits:
You can also dynamically import components or modules outside of React.lazy.
import React, { useState } from "react";
function App() {
const [Component, setComponent] = useState(null);
const loadComponent = () => {
import("./DynamicComponent").then((module) => {
setComponent(() => module.default);
});
};
return (
<div>
<button onClick={loadComponent}>Load Component</button>
{Component && <Component />}
</div>
);
}
export default App;
Benefits