DEV Community

Raushan Sharma
Raushan Sharma

Posted on • Updated on

Route-based code splitting in ReactJS

Bundling

Since decades (if not years), it has been a general practice to bundle all the javascript files in a single main.bundle.js file that will have all the codes of the project, including third party libraries.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="main.bundle.js"></script>
</head>
<body>
    <h1>Route-based code splittig in ReactJS</h1>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Separate vendor bundling

Another common optimisation technique is to define a Vendor bundle vendor.bundle.js to include all the third-party libraries in a separate bundle that can be cached much longer than your main bundle - main.bundle.js (because, presumably, you wouldn’t update your third-party dependencies nearly as much as you would update your app code).

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="vendor.bundle.js"></script>
    <script src="main.bundle.js"></script>
</head>
<body>
    <h1>Route-based code splittig in ReactJS</h1>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Problem

The above two approaches certainly works pretty well considering small single page application. However if your application grows and have multiple-routes, you will end up loading unnecessary codes that are not particularly needed for that specific route.

This can considerably affect the initial rendering of your page, and you might be already aware that how page speed affects SEO ranking of your application

You also don't want your bandwidth to be eaten-up by downloading on client side, especially on mobile devices.

For example, there is no point of loading functional codes for Home page in Contact us page.

Route-based bundling in ReactJS (16.6 and onwards)

Considering all the above problems, it does completely make sense to split the code on the basis of routes.

Here’s an example of how to setup route-based code splitting into your app using libraries like React Router 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 ContactUs = lazy(() => import('./routes/ContactUs'));

const App = () => (
  <Router>
    <Suspense fallback={<div>Loading...</div>}>
      <Switch>
        <Route exact path="/" component={Home}/>
        <Route path="/contact-us" component={ContactUs}/>
      </Switch>
    </Suspense>
  </Router>
);
Enter fullscreen mode Exit fullscreen mode

One thing here is to notice that while the component is being fetched in a lazy manner, you might see some flickering or delay based on network conditions or computation in rendering. In that case, we can take advantage of Suspense API and and pass a component in fallback like a spinner.

const Home = React.lazy(() => import('./home')); // Lazy-loaded

// Show a spinner while the home is loading
<Suspense fallback={<Spinner />}>
  <Home />
</Suspense>
Enter fullscreen mode Exit fullscreen mode

Note:
React.lazy and Suspense are not yet available for server-side rendering. If you want to do code-splitting in a server rendered app, it recommend to use Loadable Components that supports server-side rendering.

In Create React App, code-splitting is already configured for you and you can start using it immediately. It’s also supported out of the box in Next.js.

If you’re setting up Webpack yourself, you’ll probably want to read Webpack’s guide on code splitting.

If you find the article informative, please don't forget to follow.

Happy coding :)

Interested in having a look at my other articles?

Learn some of the best practices in web accessibility that will help your web content or web application reach out to a broader audience.

If you talk optimization and walk optimization, memoization is one of the basic concepts that you must add in your skillsets. Moreover you will also learn how you can easily memoize your React components.

Find out how Optional chaining and Nullish coalescing can make your code look more clean and readable.

Top comments (1)

Collapse
 
kiransiluveru profile image
kirankumar

What is server side rendering here could you explain with an example?