How to use code splitting in Reactjs
Blog React Code Splitting

In this post we are going to learn how to use code splitting in Reactjs. The process of splitting your javascript code into multiple different files instead of a single bundle is called code splitting.

What is code splitting

Previously what developers are doing they are sending the whole bundle of javascript to the user on webpage load but as the size of modern functionality increased the size of bundle is also started increasing. To avoid this problem the concept of code splitting come.

According to code splitting user should have all javascript code of page which he is currently using instead of sending whole the bundle at initial load.

What are the benefits

Code splitting have a lot of benefits but most common benefits are given below:-

  • Small javascript file size
  • Initial load will be faster
  • Better user experience
  • Lower resource required by client and server
  • Less to parse and evaluate js

How to use code splitting

There is different ways to use code splitting in your app some of them are given below

Using Dynamic Import

The way we signal to Webpack what we want to split into a separate bundle is by using dynamic imports. The import keyword can be used as a function which takes the path to the module we want to be split in a separate bundle and returns a promise.

without dynamic import

// app.js
import { add } from './math.js';

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

your bundle will be look like this

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

console.log(add(16, 26)); // 42

with dynamic import

we updated our math.js file now

// math.js
import("./math").then(math => {
  console.log(math.add(16, 26));
});

When Webpack comes across this syntax, it automatically starts code-splitting your app. If you’re using Create React App, this is already configured for you and you can start using it immediately. It’s also supported out of the box in Next.js.

React.lazy

The React.lazy function lets you render a dynamic import as a regular component. React.lazy is only available for client side rendering (CSR).

without React.lazy

import OtherComponent from './OtherComponent';

with React.lazy

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

React.lazy should always be used with suspense.

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

function MyComponent() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <OtherComponent />
      </Suspense>
    </div>
  );
}

React.lazy only works with default imports. To use with named export you need additionally create another intermediate file which gonna component as default.

Loadable-components

To use code splitting with SSR you can use loadable-components package for that.

npm install @loadable/component

Example

import loadable from '@loadable/component'

const OtherComponent = loadable(() => import('./OtherComponent'))

function MyComponent() {
  return (
    <div>
      <OtherComponent />
    </div>
  )
}

Route based code splitting

You can use React.lazy, loadable-components and react-loadable with routing to get code splitting and that will be the best approach for code splitting.

Example code splitting on Routes with React.lazy

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import React, { Suspense, lazy } from 'react';

const Home = lazy(() => import('./routes/Home'));
const About = lazy(() => import('./routes/About'));

const App = () => (
  <Router>
    <Suspense fallback={<div>Loading...</div>}>
      <Switch>
        <Route exact path="/" component={Home}/>
        <Route path="/about" component={About}/>
      </Switch>
    </Suspense>
  </Router>
);

I hope you have learned how to use code splitting in React. 🙂

Ref

You can also learn how to import browser dependent packages in SSR here.

Categories: Reactjs