@babel/plugin-syntax-dynamic-importto make use of code splitting. Create React App as well as next.js and Gatsby support Code Splitting out of the box and do not need to be configured to allow it.
React.lazy(), it can be used in React just as a regular component. It can also receive props as well as refs, contain further elements or be self-contained. The
React.lazy()method expects a function as its first parameter which will return a dynamic import. This import has to import a component which has been exported using default exports before.
<div>Application is loading</div>. This is only possible because we are using a feature which has also been added to React in version 16.6:
fallbackprop and has to be defined. Any valid React Element can be used and passed as a prop. Strings such as
<Suspense fallback="Loading ...">[…]</Suspense>are also a valid.
Suspenseelement. This will boost performance and drive the important parts of the application to load first.
Suspensein practice is image editing. In these type of cases, it can be useful to display the image to edit to the user already to give visual clues. The rest of the user interface containing the actual editing functionality will be loaded in a further step if loading the actual component is taking longer.
ImageCanvaswhich displays an image and
ImageToolbarwhich contains the editing tools for the images. Both of these elements are embraced by a Suspense element. The fallback
<div>Application loading</div>will be shown until the
ImageCanvascomponent has been loaded by the server.
ImageToolbarhas loaded, the second inner
Suspenseelement will take effect and show a message that "Image editing tools are being loaded." until it has been fully loaded.
ImageCanvascomponent is only loaded after the
ImageToolbarhas completed loading, the outer
Suspensewill prevent the
ImageToolbarfrom being displayed until the
ImageCanvashas also loaded. It will display the outer fallback message and render the components to the screen as soon as the
ImageCanvashas completed loading.
ImageToolbarhave loaded successfully and are both displayed
ImageCanvashas not finished loading and the message "Application is loading" message is displayed (independent of the status of the
ImageCanvashas loaded but
ImageToolbarhas not. In this case,
ImageCanvaswill be displayed but instead of the
ImageToolbar, a message saying "Image editing tools are being loaded." will be shown.
Suspensefallbacks allow for a greater degree of flexibility and granular decision making of which components should be shown at any time.
React.lazy()at the moment. However, in the future loading asynchronous data such as API calls should also be supported by Suspense.