How to use code splitting in React JS

How to use code splitting in React JS

What is code splitting?

Code splitting is a technique used to significantly improve the performance of large React apps. It involves splitting the code into smaller bundles and lazy loading them at runtime.

Why do we need it?

Before delving deeper into code splitting, let's understand why it is necessary in the first place.

Modern frameworks and libraries, such as React, rely on bundling tools like webpack and Rollup. These bundlers have the task of combining all the files into a single bundle file, which is loaded with the React app. However, when dealing with large apps that have a high number of files, the resulting bundle file becomes excessively large. This, in turn, degrades the performance of the app. Code splitting comes into play to address this performance issue caused by the large bundle file.

Code splitting creates smaller bundles and dynamically loads them as needed. It is supported by popular bundlers like webpack and Rollup.

How to implement it?

React provides the React.lazy and Suspense components for implementing lazy loading of bundles, which improves the overall performance of the app.

There are two ways to use code splitting:

  1. Component-based code splitting:

In a typical scenario, we import components like this:

import SomeComponent from './SomeComponent';

However, with React.lazy, we can import components lazily:

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

React.lazy returns a promise. While the promise is being resolved, we can use the Suspense component to display a fallback value, such as a loading spinner:

import React, { Suspense } from 'react';

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

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

We can include multiple lazily loaded components within the Suspense container.

  1. Route-based code splitting:

This approach is similar to route-based splitting with components inside Switch components. For this example, we will use react-router-dom, which is a popular routing library for React.

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

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

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

Conclusion

Code splitting is a simple yet powerful concept that significantly improves the performance of large-scale apps. I hope you found this brief tutorial helpful. Until next time, goodbye!