Lazy load component (w/ Suspense) in React

ref – https://beta.reactjs.org/reference/react/lazy#suspense-for-code-splitting

Lazy-loading components with Suspense

Usually, you import components with the static import declaration:

To defer loading this component’s code until it’s rendered for the first time, replace this import with:

Now that your component’s code loads on demand, you also need to specify what should be displayed while it is loading. You can do this by wrapping the lazy component or any of its parents into a boundary:

the code for MarkdownPreview won’t be loaded until you attempt to render it. If MarkdownPreview hasn’t loaded yet, Loading will be shown in its place.

First let’s look at a function delayForDemo that will delay the the lazy loading of our MarkdownPreview.

The import() returns a Promise that will be fulfilled once the module is loaded completely.

Hence, our parameter of promise receives imported components.
We do a timeout of 2 seconds, and then return the promise right after.

We then use it on the import like so:

The whole point of this is to show that while an import component is being lazy loaded, we must show the fallback Loading component.

Notice