×

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

Comparison between React and Vue

Comparison between React and Vue React, and Vue both are the two most famous libraries of JavaScript that are used for creating thousands of websites today. The React and Vue both...

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.

Difference between Controlled and Uncontrolled component in ReactJs

Controlled Component In the controlled component, the input of the form element is handled by the component rather than the DOM. Controlled components have the functions that govern the data, which...

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

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.

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.

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.

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.

React JSX

React JSX As we know, all of the React components include a render function. The Render function specifies the HTML output of a React component. JSX is an acronym of JavaScript extension that...

3 minutes read.

React Higher-Order Components

React Higher-Order Components In short form, Higher-Order Components are represented as HOC. The Higher-order component is an advanced technique to use component logic. HOC is a function that takes the component and returns the new...

2 minutes read.

React Redux

How to Use Redux with React Hooks It is an open-source library of JavaScript which is used for managing the application state. React uses the Redux to build the user interface....

5 minutes read.

React Fragments

React Fragments The fragments in React are introduced from the 16.2 and above versions. Fragments allow you to group a list of child elements without adding any extra node in the DOM. In React,...

2 minutes read.

React Props

React Props A prop is an abbreviation of ‘properties.' State and props are mainly different from each other because props are immutable. Props are the read-only components. It is the object that stores the attribute...

3 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 Refs

React Refs The word ‘Refs’ is an abbreviation of ‘References’ in React. It is as similar as Keys in React. Refs are a function in React which is used for accessing the DOM element and...

7 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 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 Error Boundaries

React Error Boundaries In the past, the errors of JavaScript within the components were used to corrupt the internal state of react and cause it to emit the cryptic errors on the next...

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