React JS and Bundling

React JS today is by far the most used front and library. The majority of the developers and organisations use this library to ship their front-end. React JS a simple easy to use and very powerful when it comes to features. I will not be talking about a lot of syntaxes in this article but we will try to understand What is bundling and what is code splitting in React.

You ask any react developer and he will surely know about the react build command but what does it do under the hood when the answer is simple it builds bundles but what are bundles let’s have a look.

When you run the build command it merges all the important files into one file and that file is called a bundle .This bundle can be loaded on the web browser to load the complete web app at once and this is why you find the react applications are so fast.


The source code of any web application written in any language is often divided into various logical units called modules. This practice makes the code easy to read and maintain and is followed throughout the developer community.  When you run npm run build  all the files which are imported via react component are merged or bundled into one file that is known as a bundle

Drawbacks of Bundling

Bundling seems nice, all the code is downloaded on the browser in one go and the user does not have to wait for the other pages to download throughout the session. But what about the drawbacks?


Once the bundle downloads, navigation through the application is very easy, but the user has to wait for the whole bundle to be downloaded before he can even see the first page of the application. This is a serious drawback.

According to research if your application takes more than 10 seconds to load the first page you can potentially lose 90% of your visitors. As you build more features, the codebase gets heavier, which also increases your bundle size.

To solve this problem we use Code spitting in React. Code Splitting is nothing but splitting a bundle into various smaller chunks which are loaded only when they are required.

 

Code Splitting in React JS

The key to code splitting in React JS is understanding which part of your application needs to use different JavaScript Dependencies. Code splitting allows to omit some dependencies from the bundle, and then fetch them only when they are needed.


For example, suppose you have a login page, and after only a successful auth you allow the user to see the rest of the website. You don’t need to fetch the complete app (as a bundle , which might take a longer time) for showing the login page. You can just fetch the bundle responsible for displaying the login page and upon successful auth, you can fetch the rest of the bundle. The user does not have to wait for the bundle of the whole application to be fetched just to see the login page. 

How to do code splitting in React JS

Code Splitting actually depends upon bundlers. A bundler is a component that actually does bundling. We might have not realized, but we use a bundle every time we run npm run build
Webpack is easily the most used bundler, and if you carefully see your react code base, you will find it. 

React has multiple methods to customize bundling regardless of which bundler you use. 

Using React.lazy

React.lazy allows lazy loading of components. The components are declared in the file, but are loaded into the bundle only when that particular component is required to be rendered. Let us look at an example to understand it better. 

import React, { Suspense } from 'react';

const lazyComp = React.lazy(() => import('./lazyComp'));

function MyComponent() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <lazyComp />
      </Suspense>
    </div>
  );
}
 

In the above example, we have imported lazyComp in line 2. But the catch is React.lazy() . The lazyComp is not actually imported and bundled when it is declared, it is actually imported and bundled when it is used when MyComponent renders. 
Any Lazy Loaded the component should be surrounded by a Suspense block. The suspense component (provided natively by React) has a fallback prop that is displayed in case importing lazyComp fails.

Dynamic Imports

This is the simplest way to split code in React JS. Dynamic imports use the then syntax.
Any reference to the imported code n

Let us look at an example. 

import("./lazyComp").then(parseText => {
console.log(lazyComp.count("This is a text string", "text"));
});



Choosing Code Splitting Points

The ultimate goal of code splitting in React is to give the end-users a smooth and dynamic experience. And thus choosing the places within your codebase to dynamically load dependencies becomes a very important and critical task.

A good place to start code splitting can react routes since users expect a slight delay when switching between pages. Dynamic code splitting on routes usually involves some dependencies of its own, but since users often expect some form of page transition, a little purposeful delay during loading might be useful.

Want to read about some interesting hacks that can make React development  easier, make sure to check out this article


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *