Using Placeholder Components during Lazy Loading
Display a placeholder or loading indicator while waiting for a lazy-loaded component to render in Next.js.
import React, { Suspense } from 'react';
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function PlaceholderComponent() {
return <div>Loading...</div>; // This is the placeholder you'll see while LazyComponent is loading
}
function MyComponent() {
return (
<div>
<h1>My Component</h1>
<Suspense fallback={<PlaceholderComponent />}> // Suspense component with fallback for lazy loading
<LazyComponent />
</Suspense>
</div>
);
}
This code demonstrates how to use React's Suspense component with a fallback placeholder while waiting for a lazy-loaded component to render in a Next.js application.