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')
    //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.


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 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 (
        <Suspense fallback={<div>Loading....</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!..

Latest comments (0)

We are hiring! Do you want to be our Senior Platform Engineer? Are you capable of chipping in across sysadmin, ops, and site reliability work, while supporting the open source stack that runs DEV and other communities?

This role might just be for you!

Apply now