DEV Community

Cover image for React: Code splitting
Ravina Deogadkar
Ravina Deogadkar

Posted on

React: Code splitting

Hi everyone! recently I was working on complex multiple module react app and also it has lots of dependencies on third party libraries. So the loading time of some of the components was beyond its expectations and the size of bundle was the other part.

Any web application will be user accessible/friendly only if the response time is lowest as possible and smaller bundle size will improvise build time and save storage.

Bundling is a process to merge all imported modules in a single files. Bundling is good when size of dependencies is small but as dependencies grow merging in a single file is a problem. Here code splitting comes in a picture, Code splitting is a feature supported by Webpack and comes pre-configured with code-react-app.

Code Splitting

It is a process to lazy load only the things that are required by our application causing speeding up the load time of our application. With code splitting the code that is never needed will not be loaded and the code size will be lower at initial build.

Dynamic imports

let sortedString = import('./StringUtils')
    .then(StringUtils=>{
        StringUtils.sort(str)
    })
    .catch(err=>{
    //handles error
   })

Enter fullscreen mode Exit fullscreen mode

In the example, StringUtils module is not imported before this code and the bundle size is smaller. When webpack comes across this syntax it automatically starts code splitting.

React.lazy

Lets you render dynamic imports as regular components. It automatically renders the bundle containing the component when it is first rendered.

let UtilsComponent = React.lazy(()=>import('./StringUtils'))

React.lazy takes a function as input that imports a module and returns a promise that resolves into a module with a default export to a component.

React.suspense

React.suspense is used to render lazy components which shows fallback component until we are waiting for lazy component to render.

import React, { Component, Suspense } from 'react'

export default class Statics extends Component {
  render() {
    let RandomColor = React.lazy(()=>import('./RandomColor'));
    return (
      <div>
        <Suspense fallback={<div>Loading....</div>}>
          <RandomColor/>
        </Suspense>
      </div>
    )
  }
}
Enter fullscreen mode Exit fullscreen mode

fallback props of React.Suspense takes any component that will be displayed until the lazy component is loaded.

So here we have solved both of are problem, our bundle size is smaller since we are dynamically importing components only when they are required. Load time is also low as the bundle size is low due to dynamically importing components.

That's all for today, until then Happy Coding!..

Oldest comments (0)