Code Splitting in React using React.lazy and Suspense

In this article, we will talk about the Code splitting in React using React.lazy and Suspense. In other words, you can also say that the lazy loading in React.

What is code splitting?

When you are working with a large scale application, you may have noticed that all your code is attached to a single bundle file. So whenever you run an application in a browser you have to wait until all the code is downloaded and your bundle file becomes large. So to avoid it, we need to split our code into different chunks.

The React.lazy and Suspense are built-in components to manage the code splitting functionality. Let’s try to understand it with an example.

Steps to implement lazy loading in React

  1. Create react application
  2. Implement routing
  3. Output before code splitting
  4. Add lazy loading in react component
  5. Output after code splitting

1. Create react application

Let’s create a simple application using create-react-app. Following article will help you to set up the application.

Create React Application

2. Implement routing

In order to show you the demo, first we will implement the routing in react application. Follow the article to get more information about the implementation of the Routing in React JS.

Here, we will create three different pages and add the link in the main component for navigation.

Home.js

About.js

Contact.js

App.js

index.css

3. Output before code splitting

The above code will create a single bundle for the entire application and download it during the first load when you run a project in the browser. Check out the below image for your reference.

Output before code splitting - Clue Mediator
Output before code splitting – Clue Mediator

4. Add lazy loading in react component

Now we will add the lazy loading in application. First we have to import lazy & Suspense from the react and re-import the three components Home, About & Contact using React.lazy.

Use the Suspense component with fallback attribute to pass the loading component.

App.js

5. Output after code splitting

Let’s check the output after the code splitting. You will see that the bundle will be downloaded on demand.

Output after code splitting - Clue Mediator
Output after code splitting – Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

Github Repository StackBlitz Project

You may also like...

Leave a Reply

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