January 5, 2022

How To Lazy Load React Components With react-lazyload

What is lazy loading?

When a user visits your website you want the page to render as quickly as possible. The user will only see the top most part of the page. Say you have lots of images showing further down the page. If the user is going to load all the images on the first page load the impression of the website will be slow and the user will fetch unnecessary data.

So instead it’s better to defer the image loading until the user actually sees them, or is about to see them. This will dramatically increase the performance, user experience and even SEO.

So how can we achieve lazy loading in a simple way? There are multiple packages that aim to solve this problem. One of my favourites and probably the most popular one is the react-lazyload package. Using a third-party package for this is something I prefer since it’s fast, performant and easy to use.

Using react-lazyload

react-lazyload is an open source package to handle lazy loading of React components, images and more. It has over 100k+ weekly downloads and makes lazy loading very simple.

To install the package run

npm install react-lazyload

Then import the component in your application

import LazyLoad from 'react-lazyload'

Then wrap the component you want to lazy load with <LazyLoad>

<LazyLoad>
	<Component />
</LazyLoad>

That’s it. This will load the <Component /> first when it is visible in the viewport.

Configure the LazyLoad component

By default the <Component /> will be hidden until it loads by the <LazyLoad> component. Depending on what type of component you want to lazy load there are some options you can use.

For images you can set a specific height to avoid layout shifts when the component loads. This can be done with the property height. Set the height to a specific amount of pixels and the component will take up that much space before being loaded.

<LazyLoad height={300}>
	<Component />
</LazyLoad>

If you want the component to render just before the user actually sees that part of the page you can use the offset property. That means you can say that load this component when the user is x pixels away from seeing it.

<LazyLoad offset={100} height={300}>
	<Component />
</LazyLoad>

This loads the component when it is 100px from coming in to the viewport. This makes the user experience better since the user will not see the actual loading and can continue scrolling unnoticed.

You can set other properties like placeholder, styling, resize events and more. Go to the official documentation to read more.

Happy lazy loading!

Thank you for reading this far! 🎉

Follow me on Twitter for more inspiration and dev tips.

Feel free to reach out if you have any feedback or questions.

Check out the blog page for more articles.