11 Code splitting with Suspense

 

This chapter covers

  • Importing code dynamically with the import function
  • Loading components when they’re needed with React.lazy
  • Specifying fallback UI declaratively with Suspense components
  • Understanding how lazy and Suspense work together
  • Specifying error fallback UI declaratively with error boundaries

It’s common for app users to interact with some components more than others. In the bookings app, for example, users often visit the Bookings page without switching to the Bookables or Users pages, and on the Bookables page they may never bring up the New or Edit forms. To manage the amount of code loaded by the browser at any one time, we can use a technique called code splitting; rather than loading all of an app’s code at once, we load it in chunks, as it’s needed.

So far in this book, all of our examples have used static imports. At the top of each JavaScript file, we include import statements to specify dependencies, the code in external files that the current file uses. At build time, bundlers like webpack inspect our code, follow the paths to the imported files, and generate a bundle, a file that contains all the code the app actually uses. Our web pages then request the bundle.

11.1 Importing code dynamically with the import function

11.1.1 Setting up a web page to load JavaScript when a button is clicked

11.1.2 Using default and named exports

11.1.3 Using static imports to load JavaScript

11.1.4 Calling the import function to dynamically load JavaScript

11.2 Importing components dynamically with lazy and Suspense

11.2.1 Converting a component to a lazy component with the lazy function

11.2.2 Specifying fallback content with the Suspense component

11.2.3 Understanding how lazy and Suspense work together

11.2.4 Code splitting an app on its routes

11.3 Catching errors with error boundaries

11.3.1 Checking out the error boundary example in the React docs