How to Split the code in the React?

If you are interested to learn about the React Hooks

Code-Splitting is a feature supported by bundlers like Webpack, Rollup, and Browserify which can create multiple bundles that can be dynamically loaded at runtime. As websites grow larger and go deeper into components, it becomes heavier. This is especially the case when libraries from third parties are included. Code Splitting is a method that helps to generate bundles that are able to run dynamically. It also helps to make the code efficient because the bundle contains all required imports and files.
Bundling and its efficiency: Bundling is the method of combining imported files with a single file. It is done with the help of Webpack, Rollup, Browserify as they can create many bundles that can be loaded dynamically at runtime.
With the help of code splitting, ‘lazy load’ can be implemented, which means just using the code which is currently needed. The bundle is responsible for loading an entire app at once on the webpage. We can understand it from the below example.

App.js

import { add } from './math.js';  
  
console.log(add(16, 26)); // 42  

math.js

export function add(a, b) {  
  return a + b;  
}  

Bundle file as like below:

function add(a, b) {  
  return a + b;  
}  
  
console.log(add(16, 26)); // 42

As our app grows, our bundle will grow too, especially when we are using large third-party libraries. If the bundle size gets large, it takes a long time to load on a webpage. For avoiding the large bundling, it?s good to start ?splitting? your bundle. React 16.6.0, released in October 2018, and introduced a way of performing code splitting. Code-Splitting is a feature supported by Webpack and Browserify, which can create multiple bundles that can be dynamically loaded at runtime. Code splitting uses React.lazy and Suspense tool/library, which helps you to load a dependency lazily and only load it when needed by the user. The code splitting improves:

  • The performance of the app
  • The impact on memory
  • The downloaded Kilobytes (or Megabytes) size

How do you separate a React code?

Perhaps the simplest way to split code in React is with the dynamic “import” syntax. Some bundlers can parse dynamic import statements natively, while others require some configuration. The dynamic import syntax works for both static site generation and server-side rendering.

What is a purpose of code splitting?

Code-splitting is the process of splitting the application’s bundle into smaller chunks required by each entry point. The goal is to improve the application’s initial load time by only loading the code required to run that page.

Why do we need code-splitting?

Every day, users visit hundreds of websites and only stay a few times. According to Google’s survey, up to 53 percent of visits are abandoned if sites take longer than 2-3 seconds to load. Performance optimization is a major key point to achieve every developer deals with. The developer does their development local where they can see less or no performance issues, but after production, once we try to navigate the application, we immediately notice the render time is high, which explains that our application is slow.

While developing on a local server, all files are hosted from a local port: 3000. However, downloading large files becomes a major issue while the application goes live, So code-splitting plays a big and major role.

React.lazy

The best way for code splitting into the app is through the dynamic import() syntax. The React.lazy function allows us to render a dynamic import as a regular component.

Before

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

After

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

The above code snippet automatically loads the bundle which contains the ExampleComponent when the Example Component gets rendered.

Suspense

If the module which contains the Example Component is not yet loaded by the function component(MyComponent), then we need to show some fallback content while we are waiting for it to load. We can do this using the suspense component. In other words, the suspense component is responsible for handling the output when the lazy component is fetched and rendered.

const ExampleComponent = React.lazy(() => import('./ ExampleComponent'));  
  
function MyComponent() {  
  return (  
    <div>  
      <Suspense fallback={<div>Loading...</div>}>  
        <ExampleComponent />  
      </Suspense>  
    </div>  
  );  
}  

The fallback prop accepts the React elements which you want to render while waiting for the component to load. We can combine multiple lazy components with a single Suspense component. It can be seen in the below example.

const ExampleComponent = React.lazy(() => import('./ ExampleComponent'));  
const ExamComponent = React.lazy(() => import('./ ExamComponent'));  
  
function MyComponent() {  
 return (  
 <div>  
 <Suspense fallback={<div>Loading...</div>}>  
 <section>  
 <ExampleComponent />  
 <ExamComponent />  
  </section>  
  </Suspense>  
  </div>  
  );  
}  

Note: React.lazy and Suspense components are not yet available for server-side rendering. For code-splitting in a server-rendered app, it is recommended to use Loadable Components.

Error boundaries

If any module fails to load, for example, due to network failure, we will get an error. We can handle these errors with Error Boundaries. Once we have created the Error Boundary, we can use it anywhere above our lazy components to display an error state.

import MyErrorBoundary from './MyErrorBoundary';  
const ExampleComponent = React.lazy(() => import('./ ExampleComponent'));  
const ExamComponent = React.lazy(() => import('./ ExamComponent'));  
  
const MyComponent = () => (  
  <div>  
  <MyErrorBoundary>  
  <Suspense fallback={<div>Loading...</div>}>  
  <section>  
  <ExampleComponent />  
  <ExamComponent />  
  </section>  
  </Suspense>  
  </MyErrorBoundary>  
  </div>  
);  

Route-based code splitting

It is very tricky to decide where we introduce code splitting in the app. For this, we have to make sure that we choose the place which will split the bundles evenly without disrupting the user experience.

The route is the best place to start the code splitting. Route based code splitting is essential during the page transitions on the web, which takes some amount of time to load. Here is an example of how to setup route-based code splitting into the app using React Router with React.lazy.

import { Switch, BrowserRouter as Router, Route} from 'react-router-dom';  
import React, { Suspense, lazy } from 'react';  
  
const Home = lazy(() => import('./routes/Home'));  
const About = lazy(() => import('./routes/About'));  
const Contact = lazy(() => import('./routes/Contact'));  
  
const App = () => (  
  <Router>  
  <Suspense fallback={<div>Loading...</div>}>  
   <Switch>  
   <Route exact path="/" component={Home}/>  
   <Route path="/about" component={About}/>  
   <Route path="/contact" component={Contact}/>  
   </Switch>  
   </Suspense>  
  </Router>  
);  

Named Export

Currently, React.lazy supports default exports only. If any module you want to import using named exports, you need to create an intermediate module that re-exports it as the default. We can understand it from the below 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"));  

How to Split the code in the React?
Show Buttons
Hide Buttons