Why Code-Splitting is a lifesaver

A Comprehensive Approach on how to implement code-splitting by lazy-loading react components.

Why Code-Splitting is a lifesaver

Photo by freestocks on Unsplash

Behind the Scenes

When we create a React app a modular structure is followed, where different parts of the application are divided into separate files or modules. The app may also depend on various third-party libraries or packages. But when this app is rendered on a browser, all these files are bundled into a single file using tools like Webpack, Rollup or Browserify. This bundling process has numerous advantages Better Performance, Ease of Deployment, Security etc.

Understanding the Problem

A web app can have multiple sections, components, routes etc. Due to these multiple components, the app grows and naturally, the bundle grows too. This leads to problems like Longer Initial Load Times, Poor Mobile Performance, and Increased Time to First Interaction.

Visualizing the problem

So consider the above example sandbox where we have a home page that on initial render does not load any component. But on click of a button renders the Name or the Contact component. Now in the browser, if we right-click and open the Sources tab and go to the src folder. We will find that during the initial render when neither Name nor Contact component has been rendered on the screen, still the Name.jsx and Contact.jsx files have been loaded into the browser. This is just like going to a restaurant and the waiter serves you the starters, main course and dessert altogether.

Sources tab

This is not an ideal case as currently for this example our Name and Contact components are very small, but imagine if these are 2 bulky components that increase our bundle size and result in a Longer Initial Load Time, which ultimately results in a very bad user experience and potential loss of clients.

Solving the problem

Imagine with respect to the above example that wouldn't be it nice that the Name and the Contact component's file loads on the browser only when the user invokes them. In simple terms, the waiter serves you the main course and the dessert only when you ask for it. This is where Code-splitting comes to our rescue, which is nothing but breaking down a large JavaScript bundle into smaller, more manageable chunks that can be loaded on demand. Code-splitting your app can help you “lazy-load” just the things that are currently needed by the user, which can dramatically improve the performance of your app. The below-provided sandbox demonstrates how we can solve the problem that we faced in the above example using code splitting.

In the below-provided Gif, you can see that due to code-splitting i.e. lazy-loading the Name and Contact component, now at the initial render only the App.js file loads. The Name.jsx and Contact.jsx loads only when we invoke them.

Understanding the Implementation

Now that we have understood how code-splitting dramatically changes the performance of a react app. Let's understand how it is implemented in terms of code. So in the above example what we are doing is we are lazy loading our Name and Contact component. Thus Lazy loading ensures that the code is fetched and executed only when it's needed, reducing the initial load burden.

Step 1: Importing the functions

For implementing lazy loading we need to import lazy and Suspense from React.

import { useState, lazy, Suspense } from "react";

Step 2: Import the components using lazy

This will automatically load the bundle containing the component files when the component is first rendered. lazy takes a function that must call a dynamic import(). This must return a Promise which resolves to a module with a default export containing a React component.

//Before:
import Name from './Name';
import Contact from './Contact';

//After:
const Name = lazy(() => import("./Name"));
const Contact = lazy(() => import("./Contact"));

Step 3: Rendering the lazy components inside a Suspense component

The lazy components should then be rendered inside a Suspense component, which allows us to show some fallback content (such as a loading indicator) while we’re waiting for the lazy component to load.

        <Suspense fallback={<div>Loading....</div>}>
           <Name /> 
           <Contact /> 
        </Suspense>

Conclusion

So we have finally reached the end of the article, and I hope this article would have helped you to understand why code splitting is important and how it can be implemented. Now you can implement code splitting using the lazy-loading method in your react apps and upgrade their performance.