a blog for those who code

Friday 4 January 2019

Lazy Loading in React using React.Lazy and Suspense

Lazy Loading is not a new concept, where you will load data on demand or in parallel. Alternatively you have eager loading where you will load all the data at once. If you would have worked with Webpack you might know Code Splitting, which means it allows your code to be split into various bundles which will be loaded on demand whenever you need it or in parallel. This is where Lazy Loading or on demand loading comes into picture.

React.Lazy and Suspense is used to do Lazy Loading in Client Side rendering. Do note that React.Lazy and Suspense is not available for Server Side rendering that means we need other module do that for us. To do Lazy loading in React we have two things to know i.e. React.Lazy and Suspense


The React.Lazy functions lets us render the components when required and not before hand i.e. Lazy Loading. The syntax of React.Lazy is React.lazy(() => import(...)). That means instead of importing directly we will as React to lazy load the component as follows:

Instead of

import MyComponent from './MyComponent'

We will use

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

What the above code will do is to load the bundle of MyComponent when MyComponent is rendered.


The React.Suspense is a component which wraps lazy components (you can also wrap more than one lazy components in a single Suspense component). This component takes a fallback prop which will be rendered while all the lazy components is getting loaded as shown below.

<React.Suspense fallback={<div>Loading...</div>}>
  <MyComponent />

Let's take the below example where we will be displaying the User Component in my App Component. To do it first we will use React.Lazy to tell React to do Lazy Loading on my User Component. Then use the React.Suspense to have a fallback when my User component is loading.

import React, { Component } from 'react';
const faker = require('faker');
const User = React.lazy(() => import('./user.js'));

class App extends Component {
  constructor(props) {

  render() {
    return (
      <div className="App">
        <React.Suspense fallback={<div>Loading...</div>}>
          <User />
export default App;

Please like and share the CodingDefined.com blog if you find it useful and helpful.

No comments:

Post a Comment