React 16.6 adds a new feature that makes code splitting easier: React.lazy() .

Let’s see how and why to use this feature with a small demo.

We have an app that shows a list of stocks. When you click on one stock it shows you a chart:

That’s all it does. You can read the full code in the github repo (also check the pull requests to see the diffs and a running version of the app for each change we’ll do).

For this post, we only care about what’s in the App.js file:

We have an App component that receives a list of stocks and shows a <StockTable/> . When a stock is selected from the table, the App component shows a <StockChart/> for that stock.

What’s the problem? Well, we want our app to be blazing fast and show the <StockTable/> as fast as possible, but we are making it wait until the browser downloads (and uncompresses and parses and compiles and runs) the code for <StockChart/> .

Let’s see a trace of how long it takes to display the <StockTable/> :

Trace without lazy loading

It takes 2470 ms to display the StockTable (with a simulated Fast 3G network and a 4x slowdown CPU).

What’s in those (compressed) 125KB we are shipping to the browser?

Webpack Budle Analyzer Report

As expected, we have react, react-dom, and some react dependencies. But we also have moment, lodash and victory, which we only need for <StockChart/> , not for <StockTable/> .

What could we do to avoid <StockChart/> dependencies to slow down the loading of <StockTable/> ? We lazy-load the component.

Lazy-loading a component

Using a dynamic import we can split our bundled javascript in two, a main file with just the code we need for displaying <StockTable/> and another file with the code and the dependencies that <StockChart/> needs.

This technique is so useful that React 16.6 added an API for making it easier to use with React components: React.lazy() .