Reading list Switch to dark mode

    Implementation of Code Splitting in React Js

    Updated 31 May 2023

    Hello, Today We are going to learn how we can reduce the load time of our created Js bundle via Webpack/Rollup/browserify, etc. from split our bundle code into various parts.

    Why We Need This?

    If you’re using Create React AppNext.jsGatsby, or a similar tool, you will have a Webpack setup out of the box to bundle your app. which creates a bundle file and that bundle file may have large third-party libraries js which is not even required on the home page, that may take a long time to load. here our code-splitting provides the solution for this problem. Hope you understand the requirement of splitting.

    Code Splitting in React Js

    Bundling is great, but as your app grows, your bundle will grow too. Especially if you are including large third-party libraries. You need to keep an eye on the code you are including in your bundle so that you don’t accidentally make it so large that your app takes a long time to load.

    Searching for an experienced
    WordPress Company ?
    Find out More

    Code splitting will “lazy-load” your component or routing. which can dramatically improve the performance of your app. Here We are not removing the code from the app. we are just loading when it is required (We are loading lazily).

    React.lazy

    This will allow you to render dynamic import as a regular component.

    Code Now :

    import FirstComponent from './FirstComponent';

    After Code Splitting :

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

    OR

    import { lazy } from 'react';
    const FirstComponent = lazy(() => import('./FirstComponent'));

    This will automatically load the bundle containing the FirstComponent when this component is first rendered.

    Now This Lazy component will be called the Suspense Component. This Suspense Component will allow us to show some content until our lazy Component Bundle doesn’t call.

    import { Suspense, lazy } from 'react';
    
    const FirstComponent = lazy(() => import('./FirstComponent'));
    
    function MyComponent() {
      return (
        <div>
          <Suspense fallback={<div>Loading...</div>}>
            <FirstComponent />
          </Suspense>
        </div>
      );
    }

    This fallback prop can accept any React element you want to render, now Loading msg will render until our <FirstComponent /> will not load.

    You can also render multiple Components under the Suspense.

    import { Suspense, lazy } from 'react';
    
    const FirstComponent = lazy(() => import('./FirstComponent'));
    const SecondComponent = lazy(() => import('./SecondComponent'));
    
    function MyComponent() {
      return (
        <div>
          <Suspense fallback={<div>Loading...</div>}>
            <FirstComponent />
            <SecondComponent />
          </Suspense>
        </div>
      );
    }

    Route-based code splitting :

    A good place to start is with routes. Most people on the web are used to page transitions taking some amount of time to load. You also tend to be re-rendering the entire page at once so your users are unlikely to be interacting with other elements on the page at the same time. Here you can use any transition in the Suspense fallback prop.

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

    Named Exports

    React.lazy currently only supports default exports. If the module you want to import uses named exports, you can create an intermediate module that reexports it as the default.

    // ManyComponents.js
    export const MyComponent = /* your code here */;
    export const MyUnusedComponent = /* your code here */;
    // MyComponent.js
    export { MyComponent as default } from "./ManyComponents.js";
    // MyApp.js
    import React, { lazy } from 'react';
    const MyComponent = lazy(() => import("./MyComponent.js"));

    Name Your Chunks

    If you want to create the split code with separate names. here you can easily achieve that with this.

    import React, { lazy } from 'react';
    const MyComponent = lazy( () =>
    	import( /* webpackChunkName: "myComponent" */ './MyComponent.js' )
    );

    This way Code Splitting may also be achieved if you are using Webpack.

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home