Code splitting in React.js

React JSJavascript LibraryFront End Technology

We bundle the files in React application using tool such as webpack. Bundling in the end merges the files in the sequence of their imports and creates a single file.

The problem with this approach is that the bundle file gets larger with the increase in files. User may not be sung all the feature components but still bundle is loading them, this could affect the loading of application.

To avoid this, code splitting is used in React.

Example

Example of bundling −

// app.js
import { total } from './math.js';
console.log(total(10, 20)); // 42
// math.js
export function total(a, b) {
   return a + b;
}

Bundle

function total(a, b) {
   return a + b;
}
console.log(total(10, 20)); // 30

The code splitting feature uses lazy loading to load only those files which are required . this can improve the performance of app considerably.

Use of dynamic import is simple use case of lazy loading −

Before

import { total } from './math';
console.log(total(10, 20));

After

import("./math").then(math => {
   console.log(math.total(10, 20));
});

The dynamic import is still not part of language standard officially. With babel, we have to use babel-plugin-syntax-dynamic-import.

React.lazy helps to import a component lazily.

import TestComponent from './ TestComponent ';
function LazyComponentLoadExample() {
   return (
      <div>
         < TestComponent />
      </div>
   );
}

After

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

Use of suspense

It’s the fallback content till the lazy loading of the component completes

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

Route based code splitting

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

As React.lazy only support the default export, the named exports are handled with an intermediate export which export them as default.

raja
Published on 28-Aug-2019 12:46:34
Advertisements