React Code Splitting

React Code Splitting

React Code Splitting is the procedure of splitting the bundle files by which the files get easily loaded on the webpage.

The react application bundles the files by using tools such as Webpack or Browserfy. The Bundling process takes multiple files and merges them with a single file, called Bundle. The Bundle is used to load the entire app at once on the webpage. You can understand it by using the following example:

Suppose there is file App.js and Math.js, then the bundle merges both files into one.

App.js

import {sub} from './Math.js';  
console.log(sub(26, 16)); // 10   

Math.js

export function sub(a, b) {  
return a - b;  
}

The Bundle file is as follows:

function sub(a, b) {
return a - b;
}
console.log(sub(26, 16)); // 10

As the application increases, the bundle also gets increases, mainly when we are using large third-party libraries. If the size of the bundle is getting large, then it will take a long time to load on the webpage.

To avoid the large bundling, we need to start the splitting of the bundle.

React version 16.6.0 released in the October 2018, and introduced the way to perform the splitting of code. The code-splitting feature is supported by Webpack and Browserify, which can create multiple bundles that can be loaded dynamically at runtime.

Code Splitting generally uses the React.lazy and Suspense tool/library, which helps you in the loading of a dependency lazily, and it only loads when the user requires it.

The code splitting improves the application performance, impact of the memory, and the downloaded Kilobytes (or Megabytes) size.

React.lazy

The best way of splitting the code into the app is by using the dynamic import() syntax. The React.lazy function allows us the rendering of a dynamic import as a regular component.

Example:

Before Using React.lazy()

import ExampleComponent from './ExampleComponent'; 
function MyComponent() {
return (
); }

After Using React.lazy()

const ExampleComponent = React.lazy(() => import('./ExampleComponent'));
function MyComponent() {
return (
); }

Suspense

The Suspense component is used to handle the output when the lazy component is rendered and fetched.

const ExampleComponent = React.lazy(() => import('./ ExampleComponent')); 
function MyFunction() { 
return ( 
Loading...
}>
); }

The fallback prop accepts the elements of React that you required to render while waiting for the component to load. We also can combine several lazy components with a single suspense component.

For Example:

const ExampleComponent = React.lazy(() => import('./ ExampleComponent'));
const NewComponent = React.lazy(() => import('./ NewComponent'));
function MyFunction() {
return (
Loading...
}>
); }

Both React.lazy and Suspense components are not available for the server-side rendering. To perform code-splitting in the server-rendered applications, it is good to use Loadable Components.

Error Boundaries

If a module fails to load like because of network failure, we will get an error. These errrors can be handled by using the error boundaries. Once the error boundary gets created, it can be used anywhere above our lazy components to display the error state.

import MyErrorBoundary from './MyErrorBoundary';
const ExampleComponent = React.lazy(() => import('./ ExampleComponent'));
const NewComponent = React.lazy(() => import('./ NewComponent'));
const MyComponent = () => (
Loading...
}>
);

Route-based code splitting

It is hard to decide where we have to introduce the code splitting in the application. For this, we need to make sure that we choose the place that splits the bundles evenly without any disrupting of the user experience.

The route is the best thing for the code-splitting. It is essential during the transitions of the page on the web that it takes some time to load.

For Example:

import { Switch, BrowserRouter as Router, Route} from 'react-router-dom'; 
import React, { Suspense, lazy } from 'react'; 
const Home = lazy(() => import('./routes/Home')); 
const Contact = lazy(() => import('./routes/Contact'));
const About = lazy(() => import('./routes/About')); 
const App = () => ( 
 
Loading...
}> );

Named Export

Now, React.lazy supports only the default exports. If any module you need to import by using named exports, then you have to create an intermediate module that re-exports it as default.

For Example:

ExampleComponents.js

export const MyFirstComponent = /* ... */;  
export const MySecondComponent = /* ... */;   

MyFirstComponent.js

export { MyFirstComponent as default } from "./ExampleComponents.js";

MyApp.js

import React, { lazy } from 'react';  
const MyFirstComponent = lazy(() => import("./MyFirstComponent.js"));