React components can be loaded when needed by using two built-in features: React.lazy()
and React.Suspense
.
React.lazy
allows you to load a component until it is rendered for the first time.
React.Suspense
enables you to display a loading indicator while a component is loading.
Using React.lazy()
React.lazy()
makes it easy to write components that are lazy-loaded but rendered like regular ones. This causes the bundle containing the component to load when the component is rendered.
Typically, we use dynamic import()
with React.lazy()
to load a lazy-loaded component, which is an official ECMAScript spec since ECMAScript 2020.
This is an example from the offical React website:
1 | import { lazy } from "react"; |
Using React.Suspense
A component imported using React.lazy()
is loaded only when it needs to be rendered. As a result, some kind of placeholder should be displayed while it is being loaded, such as a loading indicator. This is what Suspense
is designed for.
<Suspense>
is a components lets you display a fallback when its children are being loaded. We can use it as a wrapper for lazy components.
1 | <Suspense fallback={<Loading />}> |
This component takes a fallback
props that accepts a React component you want rendered as placeholder while all the lazy components get loaded.
1 | <Suspense fallback={<Loading />}> |
In this example, the component Loading
will be displayed when the MarkdownPreview
is not ready yet. When MarkdownPreview
has been loaded, the placeholder will be replaced with its content.