liveBook · Manning

Dynamic import

As explained in React Hooks in Action: With Suspense and Concurrent Mode

A dynamic import is a JavaScript import expression that asynchronously loads a module at runtime and returns a promise for its module namespace.

Dynamic import lets an application defer loading a module until a user needs it, reducing the code required by the initial bundle. A button can load a large module only after it is clicked. section 11.0 section 11.1.4

The import() expression returns a promise that resolves to the exported module object. Access default exports through module.default and named exports through properties such as module.sayHi, or destructure them after awaiting the promise. section 11.1.4

Load a module after a button click

function handleClick() { import("./helloModule").then(({default: showMessage, sayHi}) => { showMessage("messagePara", "Hello World!"); sayHi("hiPara"); }); } The module is not loaded until handleClick runs, and its exports become available when the promise resolves. section 11.1.4

Listing 11.4 Dynamically loading code with the import function (index.js)
function handleClick() {
  import("./helloModule")                                #1
    .then((module) => {                                  #2
      module.default("messagePara", "Hello World!");     #3
      module.sayHi("hiPara");                            #3
    });
}
 
document
  .getElementById("btnMessages")
  .addEventListener("click", handleClick);
#1 Call the import function to dynamically load a module.
#2 Assign the module to a local variable.
#3 Use the module properties to call the exported functions.

Shows the complete event-handler pattern: call import(), receive the resolved module, and invoke its default and named exports. section 11.1.4

How React Hooks in Action: With Suspense and Concurrent Mode covers it

How deep it goes
Explains import() promises, module export properties, promise handlers, and async/await, then connects dynamic imports to React.lazy.
Examples
Demonstrates a button-triggered helloModule load that calls default and named exports, then adapts the pattern for a lazy Calendar component.
What it assumes
Assumes familiarity with JavaScript modules and static imports while demonstrating how promises and async/await handle deferred loading.
What you can do after
Apply it via the import function to load modules on demand and consume their default or named exports asynchronously.
How it connects
Connects dynamic import with code splitting, static imports, promises, React.lazy, Suspense, default exports, and named exports.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Hooks in Action: With Suspense and Concurrent Mode. The section links point to the parts of the book it draws on.