Using Dynamic Imports

Learn how you can drastically improve the performance of your app by avoiding unnecessary loading codes on the initial run or for immediate use.

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.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy