Advanced React
Lazy Loading and Suspense
React.lazy
Lazy loading is an advanced technique you should know when you are coding big-size React applications. It allows you to reduce the application bundle size during the initial render, and only load big-size components when needed, especially components using big external libraries.
Below is the React.lazy
basic usage
// This component is loaded dynamically
const SomeComponent = React.lazy(() => import('./SomeComponent'));
React.Suspense
To lazy loading components in React, there's still one API you need to know, it's called React.Suspense
.
React.Suspense
lets you specify the loading indicator in case some components in the tree below it are not yet ready to render. In the future, you also can use this API for more scenarios such as data fetching. But for now, this is the only use case you will need React.Suspense
:
// This component is loaded dynamically
const OtherComponent = React.lazy(() => import('./OtherComponent'));
function MyComponent() {
return (
// Displays <Spinner> until OtherComponent loads
<React.Suspense fallback={<Spinner />}>
<div>
<OtherComponent />
</div>
</React.Suspense>
);
}