×

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 (
    <div>
      {/* Add your JSX content here */}
    </div>
  );
}

export default MyComponent;

After Using React.lazy()

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

function MyComponent() {
  return (
    <div>
      {/* Add your content or components here */}
    </div>
  );
}

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 (
    <React.Suspense fallback={<div>Loading...</div>}>
      <ExampleComponent />
    </React.Suspense>
  );
}

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 (
    <React.Suspense fallback={<div>Loading...</div>}>
      <ExampleComponent />
      <NewComponent />
    </React.Suspense>
  );
}

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 = () => (
  <MyErrorBoundary>
    <React.Suspense fallback={<div>Loading...</div>}>
      {/* Include components as needed */}
      <ExampleComponent />
      <NewComponent />
    </React.Suspense>
  </MyErrorBoundary>
);

export default MyComponent;

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 = () => (
  <Router>
    <Suspense fallback={<div>Loading...</div>}>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/contact" component={Contact} />
        <Route path="/about" component={About} />
      </Switch>
    </Suspense>
  </Router>
);

export default App;

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"));  

Related Topics

ReactJS Versions

ReactJS Versions The Complete set of release history of ReactJS is elaborated as follows. The complete set of full documentation of recent releases is on GitHub. S.noVersionRelease DateExplanation1.0.3.029/05/2013Initially released for public.2.0.4.029/07/2013Supporting comments...

4 minutes read.

How to use React Context

React Context React Context is used to pass the data through the component tree without passing the props down manually at the every level. In React Application, the data is passed in a top-down approach...

4 minutes read.

React Forms

React Forms Forms are the important part of any web application. It allows the interaction of the user with the app as well as the gathering of the information from the...

3 minutes read.

React Bootstrap

React Bootstrap React has a widely used JavaScript framework for creating web applications, and Bootstrap has become the most popular CSS framework. Single-page apps have become popular from the last few...

9 minutes read.

React Component Life-Cycle

React Component Life-Cycle In ReactJS, the creation process of every component includes several lifecycle methods. These methods, together stated as component's lifecycle. Four phases of the component's life cycle are as...

4 minutes read.

Difference Between React Flux and MVC

React Flux vs MVC MVC MVC is an acronym of 'Model View Controller.' It is the architectural pattern that is used to develop the user interface. It has three different logical components: The...

2 minutes read.

ReactJS Tutorial

ReactJS Introduction React Tutorial helps you to understand the basic and some advanced concepts of ReactJS. As of now, it is the essential front-end library that is developed by a...

3 minutes read.

React Table

React Table The table represents an arrangement that organizes the information in the form of rows and columns. The table is mainly used for storing and displaying the data within a structured format. Features of...

2 minutes read.

React Flux

React Flux Introduction It is an application architecture that is internally used by Facebook to build the client-web application with react. It is useful when the project includes dynamic data, and...

2 minutes read.

Pros and Cons of ReactJS

Pros and Cons of ReactJS There are various advantages, and disadvantages of ReactJS are as follows: Benefits of ReactJS 1. Easy to Learn and Use: ReactJS is very easy to use and learn. It has a good...

3 minutes read.

React Environment Setup Step by Step

React Environment Setup This section will provide you the information about how to set up an environment for the successful development of ReactJS application: Pre-Requisite for ReactJS NodeJS and NPMReact and React DOMWebpackBabel There are two...

5 minutes read.

React Props Validation

React Props Validation As we know, props are a suitable mechanism for passing the read-only attributes to react components. The props are required to be correctly used in the component. If it is...

5 minutes read.

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...

4 minutes read.

React Router

What is React Router? Routing is a process by which a user can direct to different pages based on their actions and requests. ReactJS router is generally used to develop single...

10 minutes read.

React Events

React Events An event is an action that triggers a response of the user action or system-generated event. As HTML, React can also perform actions based on user events. React has the...

2 minutes read.

React Conditional Rendering

React Conditional Rendering In React, the working of the conditional rendering is similar to the condition works in JavaScript. We use JavaScript operators for creating elements that represent the current state, and then the React...

3 minutes read.

ReactJS vs AngularJS

Difference between ReactJS and AngularJS AngularJS AngularJS is the JavaScript framework that is open source, and it is also used to build a dynamic web application. It is developed in 2009 by...

5 minutes read.

React Keys

React Keys A key can be defined as a unique identifier. In React, it is used for identifying the items that have changed, deleted, and updated from the lists. React Keys are helpful...

3 minutes read.

React Lists

React Lists Lists are used for displaying the data in an ordered format and mainly used to display the menus on websites. The creating of lists in React is as similar...

2 minutes read.

React Animation

React Animation The animation is a procedure in which an image is manipulated to appear as a moving image. It is widely used to create an interactive web application. In React, we have to...

4 minutes read.