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 manipulating, optimizing, and delivering images and video, optimized for every device, at any bandwidth. The Cloudinary React SDK provides image and video manipulation, 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 cloudName=“demo” loading=“lazy” publicId=“sample” width=“400” crop=“scale”/>

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

Laravel File Upload to a Local Server Or to the Cloud

Currently, Laravel is the most renowned PHP framework, boasting of a large developer community; several open-source packages, such as Cashier, Sanctum, Scout, and Telescope; and a host of paid platforms, e.g., Laravel Forge, Envoyer, and Vapor. Laravel Forge & Envoyer ably supports deployment and use of Laravel production-based apps.

Read more
TedsVintageArt.com Automates Generation of Captivating Product Images on Cloudinary

At TedsVintageArt.com, we digitally restore historic maps and sell their art prints on multiple platforms, such as Amazon, Etsy, eBay, and Houzz. As our operations ramped up years ago, it took an inordinately long time to generate custom images for our products. Plus, since we sell art, it behooves us to produce multiple high-quality images for each print, which was another time-consuming task.

Read more
lastminute.com Takes a Vacation From Media-Management Headaches With Cloudinary

As a 20-year online leader in travel and leisure retail, Europe-based public company lastminute.com along with its 1,200 employees are committed to enriching the lives of vacationers through comprehensive and enticing products and services. Beyond flight deals and tours, it's the images and videos, whether of that luxury villa in Greece, romantic Parisian street, or exotic stroll through the Marrakech markets, that attract audiences and boost bookings.

Read more