𝗟𝗮𝘇𝘆 𝗟𝗼𝗮𝗱𝗶𝗻𝗴 𝗶𝗻 𝗥𝗲𝗮𝗰𝘁

Large React apps create big JavaScript bundles. Big bundles slow down your site. Users wait longer to interact with your app. This hurts your user experience.

Lazy loading solves this. It loads components only when users need them. You stop loading everything at once.

Benefits of lazy loading:

How to use React.lazy() React provides a function called lazy() to import components dynamically. React downloads the code only when it renders the component.

Example code: import { lazy } from "react";

const ProductDetail = lazy(() => import("./pages/ProductDetail"));

You must use Suspense with lazy components. Suspense shows a fallback UI while the component loads.

Example code: import { Suspense, lazy } from "react";

const ProductDetail = lazy(() => import("./pages/ProductDetail"));

function App() { return ( <Suspense fallback={

Loading...
}> ); }

Two rules for success:

  • Your components must use default exports.
  • Declare your lazy imports outside your component functions.

Do you use lazy loading in your projects? Leave a comment below. I will reply to you.

Source: https://dev.to/madhubankhatri/lazy-loading-in-react-improve-performance-with-reactlazy-and-suspense-5edk