Create a separate file for the component you want to lazy load
// Products.js
import React from 'react';const Products = () => {
return <div>This is a lazy-loaded component!</div>;
};
export default Products;
Use React.lazy()
to import the component dynamically in your route file
const Prodcuts = React.lazy(() => import("./components/products/Products"));
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
// import Prodcuts from "./components/products/Products";
import PageNotFound from "./components/PagenotFound/PageNotFound";
import {
createBrowserRouter,
createRoutesFromElements,
Route,
RouterProvider,
} from "react-router-dom";
import Home from "./components/Home/Home";const Prodcuts = React.lazy(() => import("./components/products/Products"));
const router = createBrowserRouter(
createRoutesFromElements(
<Route path="/" element={<App />}>
<Route path="/" element={<Home />}
<Route
path="prodcuts"
element={
<React.Suspense fallback={<>...</>}>
<Prodcuts />
</React.Suspense>
}
/>
<Route path="*" element={<PageNotFound />} />
</Route>
)
);
const root = ReactDOM.createRoot(document.getElementById("root"));
In the code above, the product component is loaded lazily using React. lazy(). The Suspense component is used to specify a fallback UI while the lazy-loaded component is being loaded.
Run your application:
When you navigate to the /products route, the ProductsComponent will be loaded only when needed.
Note: The fallback prop of Suspense is required. It defines the UI that will be displayed while the component is being loaded. You can customize this UI based on your application’s design and requirements.