This is a quick start for using lazy and Suspense in React. We’ll start simply by showing how to use lazy and Suspense.
For the most basic of examples, we’ll import a component lazily and render it.
We start off by importing lazy and Suspense from React:
import { lazy, Suspense } from 'React';
Next, we need to create a variable to store a Promise that is returned from the React.lazy() function. This promise will resolve into a React component.
const MyComponent = lazy(() => import('./components/myComponent');
And to render MyComponent:
<Suspense fallback={<div>Loading...</div>}>
<MyComponent />
</Suspense>
It’s important to note that the component that you want to lazily load needs to be rendered as a child of a Suspense component.
The Suspense component requires a prop named fallback that is of the type of any valid React element. This will be shown while waiting for your lazily loaded component to render.
And putting it all together into a simple component that lazily renders another component:
import { lazy, Suspense } from "react";
function App() {
const MyComponent = lazy(() => import('./components/myComponent');
return (
<h1>My lazy component</h1>
<Suspense fallback={<div>Loading...</div>}>
<MyComponent />
</Suspense>
);
}