DEV Community

mohammed afif ahmed
mohammed afif ahmed

Posted on

Introduction to code-splitting in reactjs.

Introduction

Imagine you have an application with many different components and pages with routes for that pages. So when you run your application it takes a large amount of time time to load or display content. So what the problem and how can it be solved.

That's when code-splitting comes in, it makes sure only those components are fetched which are being displayed on the webpage at that particular moment. For example, if you have a Homepage component and an AboutUs component. Homepage component is displayed when you're on root route i.e., / and AboutUs at /about, When you're on the home route you don't need AboutUs javascript right? but it is fetched on the initial load, which makes the site load time-consuming, and eventually leads to losing viewers.

We will look at an example site and how to perform code-splitting with just a few lines of code.

Let's get started:

fork or clone (might give a star as well 😀) this repo from GitHub, it is a single page application built using react. You can apply code spitting anywhere in the components. For example, where you import any third-party library. But an easier place to identify is at the route level, where you write the routing rules.
In the repo, you clone navigate to/src/MainComponent.js to see all the routes.

We have a route called /pricing which renders the PricingPage.js component, we will split this particular component.

But, before applying code-splitting let's see what the browser fetches or tries to load.

  • Start the app To start the app run the below commands(assuming you have some react knowledge)
$ npm install
$ npm start 
Enter fullscreen mode Exit fullscreen mode

The app must be live at http://localhost:3000

In Chrome dev tools open the network tab and select js as a filter, you can see that on the initial page load the browser fetches bundel.js.
network-beforeThis is where react takes all the javascript written in the application and it into this file(it contains all the components).
indexThe index page contains all the js.
As a result, the page load is slow. We are going to exclude some components from going into that bundle and instead fetch only when needed, here when someone navigates to /pricing.

The latest version of React uses a combination of two things to accomplish this: Suspense and React.lazy.

Replace the code in MainComponent.js with the below code:

import React, { Component, Suspense, lazy } from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import HomePage from './HomePage';
import ProductDetailsPage from './ProductDetailsPage';
import HowItWorks from './HowItWorks';

const PricingPage = lazy(() => import('./PricingPage'));

class MainComponent extends Component {
    render() {
        return (
            <Suspense fallback={<h1>Loading.....</h1>}>
                <BrowserRouter>
                    <Route exact path='/' component={HomePage} />
                    <Route
                        exact
                        path='/products/:productId'
                        component={ProductDetailsPage}
                    />
                    <PricingPage exact path='/pricing' />
                    <Route exact path='/working' component={HowItWorks} />
                </BrowserRouter>
            </Suspense>
        );
    }
}

export default MainComponent;
Enter fullscreen mode Exit fullscreen mode

Now go back to the network tab and check the source, you can see one more 1.chunk.js file when you navigate to /pricing
which contains only the PricingPage component.

Also when you do npm run build it builds the components separately unlike bundling all together if not using code splitting. Below are the logs of build logs before and after applying code-spitting.

File sizes after gzip:

  76.03 KB  build/static/js/2.d23bfa23.chunk.js
  28.43 KB  build/static/js/main.b229bef3.chunk.js
  770 B     build/static/js/runtime-main.e43a4c19.js
  306 B     build/static/css/main.0fc1fc64.chunk.css
Enter fullscreen mode Exit fullscreen mode
File sizes after gzip:

  76.03 KB (-2 B)    build/static/js/2.8bab3079.chunk.js
  28.07 KB (-368 B)  build/static/js/main.b6b9360c.chunk.js
  1.18 KB            build/static/js/3.58e0fecc.chunk.js
  1.16 KB (+418 B)   build/static/js/runtime-main.01e4ec24.js
  306 B              build/static/css/main.0fc1fc64.chunk.css
Enter fullscreen mode Exit fullscreen mode

As you can see there is one extra file that is our js for PricingPage component, and also you can see the reduction in the size of other files because the pricing component is excluded from that.

And...that's a wrap, I hope you have learned how to go about splitting a react app, now you can apply the same approach to your application as well.
We looked at code-splitting with react-router a create-react-app template that uses webpack under the hood, but you can apply the same with parcel, babel, etc.

Liked the post?
ko-fi

Top comments (0)