When you deploy a React application using a tool like webpack, you’re employing a technique called bundling.

Build tools like webpack are, after all, module bundlers.

So when you arrive at a page served by a web application, the page requests a bundle — that is, a file or files that contain all of the code necessary for that page to function.

Often when we build a page, however, we include quite a bit of code that isn’t immediately necessary.

To keep our application lean and fast, we should strive to serve only what’s absolutely necessary for the UI on first paint.

One way to achieve this is by code-splitting.

Code-splitting allows us to defer the loading of various resources until later — when they’re actually needed.

For example, let’s say a user hits a route and arrives at a page in your web application.

Maybe this page has a number of heavy modals.

Maybe this page has a number of routes that load additional content elsewhere.

Maybe it contains a heavy library that is needed later but is being loaded first on the home page.

If our goal is to render the page content as fast as possible, we need to abstract away everything that isn’t immediately required and is acting to slow your load time down.

Let’s explore a few ways to code-split your web app using React’s lazy method and Suspense component.


First, let’s bootstrap a project with create-react-app.

Excellent, we have the basic spinning React logo we’re accustomed to.

Open the project in your favorite editor, and let’s get started.

Project Setup

In React, we have the ability to import a function called lazy and a component called Suspense.

What lazy does is allow us to defer the loading of a component or resource until it’s needed.

#programming #react #code #javascript

Code-Split Your React App With Lazy and Suspense
1.10 GEEK