MENU
React.lazy()
React.lazy() renders an imported component dynamically.
The fallback prop accepts any React elements to be rendered while the site is waiting for the component to load. Below, if the module fails to load (for example, due to network failure), it will trigger an error, which an error boundary higher in the tree can catch to show a nice fallback UI instead of crashing the whole app.
import React, { Suspense } from 'react';
import MyErrorBoundary from './MyErrorBoundary';
const OtherComponent = React.lazy(() => import('./OtherComponent'));
const AnotherComponent = React.lazy(() => import('./AnotherComponent'));
const MyComponent = () => (
<div>
<MyErrorBoundary>
<Suspense fallback={<div>Loading...</div>}>
<section>
<OtherComponent />
<AnotherComponent />
</section>
</Suspense>
</MyErrorBoundary>
</div>
);(As of React 18, React.lazy() also works during server-side rendering, as long as you use one of the streaming SSR APIs — renderToPipeableStream or renderToReadableStream — that support Suspense; frameworks like Next.js handle this integration for you automatically.)