Lazy Load React Component

Arpit Malik
3 min readDec 9, 2020

In this tutorial we are going to learn how we can load the react components when they are needed. The technique of downloading only what you need is Lazy Loading. Sometimes loading the entire bundle with all the code can be bad if you have a bigger application. There might be some area in the application where not all users will visit. So it would be better to not download all the code upfront. This technique is useful when you have a big application else it’s not worth to make a call to get the bundle again.

The 16.6 or higher version of react adds a method to React Object the Lazy method which you can use to load the component asynchronously meaning code behind the component is only loaded when they are required.

We will take an simple example where we will load the application without using lazy method of react object and we see that the all the code is loaded at the start of application in advance and after that we will use react Suspension to see the difference between downloading of the bundles.

Components loading
Bundle

In the above code we have simply created two link and on clicking Component 2 link, bundle.js already contains all the code in the network tab.

Lazy Loading
Lazy bundle

Now in the above code we have used lazy method of react object to load the component 2 when the link Component 2 is clicked and render it what it is needed and we can see the chunk.js is downloaded when the link is clicked. There is one fallback property of Suspense component which is used to be shown or render until the component is being loaded.

Wrap Up

We have seen how we can download the code only we it is needed. This technique is used when the application is big and it is worth calling the server and downloading the code when it is needed.

Happy Coding :)

--

--