Lazy loading is a technique that defers loading of non-critical resources at page load time. Instead, these resources are loaded only when needed. In React, this is achieved throughReact.lazy() andSuspense which allow you to render a loading indicator while waiting for components to load.
Click the button below to load a component that is imported with React.lazy(). You'll see a loading indicator while the component is being fetched.
// In your page file (e.g., LazyLoadingPage.tsx)
import React, { useState, Suspense, lazy } from "react";
// Lazy load the component
const LazyComponent = lazy(() => import("@/components/LazyComponent"));
export default function LazyLoadingPage() {
const [isComponentLoaded, setIsComponentLoaded] = useState(false);
const loadComponent = () => {
setIsComponentLoaded(true);
};
return (
<div>
{!isComponentLoaded ? (
<button onClick={loadComponent}>
Load Component
</button>
) : (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
)}
</div>
);
}
// LazyComponent.tsx
import React from "react";
const LazyComponent = () => {
return (
<div>
<h2>Lazy Loaded Component</h2>
<p>This component was loaded only when needed!</p>
{/* Heavy component content goes here */}
</div>
);
};
export default LazyComponent;