Cloudinary Blog

Lazy-Load React and Boost Page Performance for Your Apps

 Lazy-Load React to Enhance Page Performance for Your Apps

React is a popular open-source JavaScript library for creating user interfaces (UIs) for single-page web applications, with React Native slated for building mobile apps. Helpfully, React organizes UIs into collections of reusable components, rendering feature management a cakewalk. However, to boost user engagement, conversion, and SEO ranking, you must optimize your app for fast page loads.

This article shows you how to perform lazy-loading with React components and then optimize images with Cloudinary to further enhance page performance. Here are the topics:


How to Optimize for Page Load Speed


What Is Lazy Loading?

Lazy loading, sometimes called on-demand loading, is a practice for improving the performance of websites and web apps. With lazy loading, you prevent users from loading your site all at once, displaying only the content that is currently or will soon be visible. As the user moves through your site and scrolls into the viewpoint, lazy loading loads only the content that is relevant at that point.

Lazy loading yields numerous benefits, especially if your sites or apps are image or media heavy. In particular, load times are shorter because less content is transferred at the same time, minimizing issues caused by limited bandwidth and requiring fewer resources from the user’s device, web servers, and networks.

What Is React and What Are Its Components?

Again, React is an open-source JavaScript library for building interactive UIs. It was developed by Facebook and has been adopted by a wide range of projects and companies, frequently in combination with other libraries to build single-page web apps.

Recall that React divides UIs into collections of reusable components with which you as developers can modify the various aspects of your UI and monitor the status of its capabilities. According to Dan Abramov, creator of Redux and a member of React’s core team, the Facebook codebase contains over 20,000 React components.

React components are JavaScript functions or classes that accept input and return React elements, which define how a portion of the UI appears to users.

Functional Components

Sometimes called stateless or dumb components, functional components are presentational, predictable, and concise. Given specific input, these components always return the same output—a reliability that makes them the preferred implementation method.

Here’s an example of a simple functional component:

const Greeting = () => <h1>Hi, I’m a functional component!</h1>;

Class Components

Sometimes referred to as smart, stateful, or container components, class components are implemented through classes, enabling you to add logic for event handling, to manage local states, and to add lifecycle methods.

Use class components only for managing local states.

Here’s an example of a simple class component:

Copy to clipboard
class Greeting extends React.Component {
  render(){
    return <h1>Hi, I’m a class component!</h1>;
  }
}

For details on React libraries, see the post How to Develop a React Library.

What Are the Lazy Loading Components in React?

Built into React are two components for lazy loading, React.lazy and React.Suspense.

React.lazy

React.lazy is a method for defining a dynamically loaded component so that you can code-split components within an application with dynamic imports.

Typically, React applications contain many components, such as standalone ones that serve as libraries for reuse by developers. Code-splitting helps boost the performance of React applications by significantly reducing the number of components that are loaded simultaneously.

To use React.lazy, first add a React.Suspense component higher in your rendering tree.

React.Suspense

React.Suspense is a component for specifying loading indicators when components that are lower in the tree have not yet rendered. To define indicators with React.Suspense, specify a fallback property, such as a spinner.

You can wrap multiple lazy components in a single React.Suspense component, and components can reside deep inside your tree. In general, use React.Suspense to add a loading indicator and React.lazy to split code.

How Do You Lazy-Load in React With `React.lazy` and `React.Suspense`?

The procedure below walks you through the steps of lazy loading in React with React.Suspense and React.lazy through an example of lazy-loading the Login component located at ./Components/Login. Be sure that you’re running React version 16.6.0 or higher. For more details, see the full tutorial by Abhimanyu Chauhan. The source code for that tutorial is on GitHub.

As a preliminary step, export the module with the following commands:

Copy to clipboard
export default Login;
export const abc = className; **Not Valid **

Step 1. Import the Login component with React.lazy.

React.lazy accepts the import() function and returns a promise from the dynamic import-invocation. Later on, the promise is resolved to lazy-load the module as required, returning a new bundle with the Login component added to the previous code.

Copy to clipboard
const Login = React.lazy(() => import(‘./Components/Login’));

Step 2. Display the fallback content with React.Suspense.

This step defines the fallback content for display while Login is being loaded.

First, import the Suspense module from React:

import React,{Suspense} from ‘react’;

Now use the Suspense component to wrap the Login component, which is dynamically imported by React.lazy. In this case, show the message “Loading …” when content loading is in progress, like this:

<Suspense fallback={<div>Loading …</div>}><Login /></Suspense>

Note
The React.Suspense API might undergo several revisions before becoming relatively stable.

Step 3. Verify that lazy loading is working.

Test with the developer tools in Chrome on a live page to see if lazy loading is working, as follows:

  1. Look for 0.chunk.js, a bundle that is initially loaded without the dynamic import performed by React.lazy.
  2. Look for 1.chunk.js, which is called when React.lazy imports the Login component.

How Do You Boost Page Performance With Cloudinary?

Cloudinary is a cloud-based service that simplifies and automates the process of transforming, optimizing, and delivering images and video, optimized for every device, at any bandwidth. The Cloudinary React SDK provides image and video transformation, optimization, and delivery capabilities that integrate seamlessly with your existing React application. Now that Lazy Loading is supported through modern browsers, you can use our SDK Image tag to Lazy Load your resources.

It is as simple as adding the attribute loading=“lazy”. For example:

Copy to clipboard
<Image 
  public-id="sample" 
  loading="lazy"
  width="400"
  height="300">
</Image>

After you optimize performance with lazy loading, you should strive to reduce image size as much as possible, to further reduce page load time. Cloudinary can help with the following features:

  • Smart quality optimization—enables you to automatically compress images without losing quality. You can achieve that by adding q_auto to your URLs, as explained in this guide about automated image compression.
  • Automated file formatting—enables you to serve the correct file format for your browser. You can do that by adding Cloudinary's f_auto flag to your URL, as explained in this guide about automated image reduction.
  • Optimize progressive images—enables you to render with the correct method. Cloudinary provides four different options: non progressive, steep progressive, semi progressive, and default progressive (fl_progressive). You can find more information in this guide about Progressive JPEGs and green Martians.

Sign up for Cloudinary today—we offer generous free plans to get you up and started.

Want to Learn More About Lazy-Loading?

Recent Blog Posts

Maya Shavin: How I Built My Website

Besides working as a senior front-end developer at Cloudinary, I'm also a content creator, a blogger, and an open-source developer. Follow me at @mayashavin and on mayashavin.com.

In the beginning, my website, mayashavin.com, was mainly for showcasing the status of my development projects and keeping me organized with my speaking schedule. Initially, I built it with Vue.js, later on switching to Nuxt.js (aka Nuxt) for a higher SEO score, and deployed it with Netlify. After some time, I added a blog section with Netlify CMS as the content management system (CMS). Everything was fine until I added more content and features, which led to a significant decline in the site’s performance. Also, the site design needed a modern look. So, I gave the site a makeover.

Read more
Automation Frees Up PetRescue’s Staff to Help Pets Find Their Forever Homes

As we spend more time at home, many of us are adopting pets for the joy, companionship and a surprising range of health benefits. In Australia, where our nonprofit customer PetRescue is located, there’s a shortage of pets to adopt. Last August, the Guardian reported that dog shelters in Australia emptied and adoption fees for puppies were running as high as $AUS1800.

Read more
Cloudinary and Contentful Make Modern Content Management Easier

I am pleased to share that Cloudinary and Contentful have joined forces to further streamline the creation, processing, and delivery of online content through Cloudinary’s digital asset management (DAM) solution and advanced transformation and delivery capabilities for images and video. What’s more, the partnership delivers a headless approach to DAM. By leveraging APIs for media management tasks, marketers and developers alike benefit from an integrated stack of optimized assets for optimization and automation. As a result, page loads are fast and beautiful, and at scale—with less overhead and effort.

Read more
Introducing Cloudinary's Nuxt Module

Since its initial release in October 2016 by the Chopin brothers as a server-side framework that runs on top of Vue.js, Nuxt (aka Nuxt.js) has gained prominence in both intuitiveness and performance. The framework offers numerous built-in features based on a modular architecture, bringing ease and simplicity to web development. Not surprisingly, Nuxt.js has seen remarkable growth in adoption by the developer community along with accolades galore. At this writing, Nuxt has earned over 30K stars on GitHub and 96 active modules with over a million downloads per month. And the upward trend is ongoing.

Read more
How Quality and Quantity can go Hand in Hand

When it comes to quality versus quantity, you’ll often hear people say, “It’s the quality that counts, not the quantity”. While that’s true in many situations, there are also cases where you want both quality and quantity. You may have thousands of images on your website and you want them all to look great. This is especially important if your website allows users to upload their own content, for example, to sell their own products or services. You don't want their poor quality images to reflect badly on your brand.

Read more