React Lazy Loading

React Lazy Loading

Oct 26, 2022ยท

2 min read

Play this article

Hello World !!

There are so many web applications running right now, which have so many things in single page.

This type of web applications may contains large amount of contents takes more time to load on screen and create performance issues.

What is lazy loading ?

It is an optimization technique which prevents whole application from loading at once. Instead required important UI elements gets render first and less important UI elements will render later as and when required.

This can be useful when we are dealing with pages/application with large amount of contents which may cause performance related issues.

What we need ....

To implement this technique, we need to things,

  • lazy() - This function is going to enable dynamic import as a regular component. This function eliminates the need to use third-party library.

  • Suspense Component - This component will show fallback contents (ex: Loading...) While waiting for our lazy component to be loaded.

This two things is directly imported from react only, no any extra things required to install in our react app.

Let's Start Coding .....

First, Create react project and open in your preferred IDE. For our example, we are going to work with mainly two files.

  • App.js

In App.js file, you can see, we have use lazy() while importing other component. Also, we have defined that lazy imported component inside the Suspense component with fallback of Loading... text.


  • HeavyComponent.js

in HeavyComponent.js, we have defined just some simple things like one h2 tag only. But, In real cases this kind of file contains so many contents.


What it looks like at the end ....

To show the concept, Have lowered my network speed to Slow 3G from dev tools.

Screenshot (8).png

  • Without Lazy Loading ...

Untitled video - Made with Clipchamp.gif

  • With Lazy Loading ...

Untitled video - Made with Clipchamp (1).gif

As you can see, without lazy loading, When all components is render then we are getting result on screen (UI Generated). But, in case of With lazy loading, first component of Hello World !! is rendered and UI is also generated but till other heavy component is rendered we are seeing fallback details (in our case,Loading ... text, mentioned as fallback option).


In today's blog, we talked about React Lazy Loading and created one simple example for the same.

Thank you for reading, I hope you found this article useful.

If you enjoyed reading, please consider following me here on Hashnode and also you can reach me at Twitter / GitHub / LinkedIn.