Member-only story
Lazy-Loading React Components
Optimize production builds with code splitting
Code splitting is a very useful tool when it comes to reducing the size of your builds. It allows you to parse (or split) your code into different bundles that can be loaded conditionally based on what is currently needed.
Let’s say you have a suite of e-learning applications for different classes and levels of education. You can compile all of the code for each of those apps into one build file that gets served to the browser when you hit the landing page (which contains links to all the apps).
As long as your build file isn’t too large, this method of compilation isn’t a bad idea. However, if you add new features, apps, or packages to your project, that bundle file can get pretty large.
If your build file is too large, it can slow down the load time for your React app. This can have a negative impact on the user experience. Don’t you hate sluggish load times?
Picture this: You have a very small bundle file for the landing page (which only needs to render links to the myriad of e-learning apps) and then other small bundles for each app that get loaded only if you enter a specific application.
Why do you need the bundle file for English II (or for the other applications in the suite) when you’re only trying to use English I? Code splitting can remedy the situation by separating out relevant code based on your entry point, thus taking code out of the main bundle and reducing its size.
In this article, I’ll go over how to implement code splitting using built-in React functions and components with no libraries or extra configuration needed.
First, here are all of the routes for our application:
With the addition of a built-in React function and component, we can split up the bundle for the code above into separate bundles for each of them in just two steps. Below is the function we will be using, which is called React.lazy
.