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:

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

Our $2B Valuation

By
Blackstone Growth Invests in Cloudinary

When we started our journey in 2012, we were looking to improve our lives as developers by making it easier for us to handle the arduous tasks of handling images and videos in our code. That initial line of developer code has evolved into a full suite of media experience solutions driven by a mission that gradually revealed itself over the course of the past 10 years: help companies unleash the full potential of their media to create the most engaging visual experiences.

Read more
Direct-to-Consumer E-Commerce Requires Compelling Visual Experiences

When brands like you adopt a direct–to-consumer (DTC) e-commerce approach with no involvement of retailers or marketplaces, you gain direct and timely insight into evolving shopping behaviors. Accordingly, you can accommodate shoppers’ preferences by continually adjusting your product offering and interspersing the shopping journey with moments of excitement and intrigue. Opportunities abound for you to cultivate engaging customer relationships.

Read more
Automatically Translating Videos for an International Audience

No matter your business focus—public service, B2B integration, recruitment—multimedia, in particular video, is remarkably effective in communicating with the audience. Before, making video accessible to diverse viewers involved tasks galore, such as eliciting the service of production studios to manually dub, transcribe, and add subtitles. Those operations were costly and slow, especially for globally destined content.

Read more
Cloudinary Helps Minted Manage Its Image-Generation Pipeline at Scale

Shoppers return time and again to Minted’s global online community of independent artists and designers because they know they can count on unique, statement-making products of the highest quality there. Concurrently, the visual imagery on Minted.com must do justice to the designs into which the creators have poured their hearts and souls. For Minted’s VP of Engineering David Lien, “Because we are a premium brand, we need to ensure that every single one of our product images matches the selected configuration exactly. For example, if you pick an 18x24 art print on blue canvas, we will show that exact combination on the hero images in the PDF.”

Read more
Highlights on ImageCon 2021 and a Preview of ImageCon 2022

New year, same trend! Visual media will continue to play a monumental role in driving online conversions. To keep up with visual-experience trends and best practices, Cloudinary holds an annual conference called ImageCon, a one-of-a-kind event that helps attendees create the most engaging visual experiences possible.

Read more