Using Dynamic Imports
Explore how dynamic imports enable code splitting in React applications. Understand how to use React.lazy with dynamic import syntax to lazy load components, reduce bundle size, and improve app performance by loading resources only when needed. This lesson covers practical examples and the use of React.Suspense for loading states.
We'll cover the following...
Dynamic import syntax
Dynamic import syntax is an extension of this syntax and allows us to dynamically lazy-load imports. Dynamic imports are similar to a Promise:
// greeter.js
export sayHi = (name) => `Hi ${name}!`;
// app.js
import("./greeter").then(greeter => {
console.log(greeter.sayHi('Manuel'));
});
When Webpack finds a dynamic import, it will automatically perform code-splitting and put this file into its own chunk. These chunks are loaded independently once they are needed within the application—which is why this process is named lazy loading.
Lazy loading of components with React.lazy()
Let’s talk more about lazy loading in React. To make the experience of performing lazy loading more enjoyable, React offers its own method from version 16.6 onward to dynamically lazy load components. It is combined with dynamic import syntax and allows the developer to easily load certain components only when the application has started running. This further reduces the size of the bundle.
Even though a component might have been loaded via 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 that has been exported using default exports before. Let’s see an example.
import React from 'react';
const LazyLoaded = () => (
<p>This component is only loaded by the server once it is in use.</p>
);
export default LazyLoaded;This method allows us to easily optimize the size of our JavaScript bundle and only load certain files from the server when the user actually requests them. During the time it takes to load and receive the data from the server to when it is executed, we’ll see information informing us that:
<div>Application is loading</div>
This is only possible because we are using a feature that has also been added to React in version 16.6 which is React.Suspense.