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

A New, Simple Tool for Creating Text Overlays for Images

Many Cloudinary users desire a UI for tasks like creating text overlays for images, which they then embed on webpages or download for marketing campaigns. Generating such overlays with the Cloudinary Media Library UI involves a bit of a learning curve, especially if they require multiple fonts or text lines, which even experienced users might find challenging to implement.

Read more
Transitioning JPEG-Based to JPEG XL-Based Images for Web Platforms

When the JPEG codec was being developed in the late 1980s, no standardized, lossy image-compression formats existed. JPEG became ready at exactly the right time in 1992, when the World Wide Web and digital cameras were about to become a thing. The introduction of HTML’s <img> tag in 1995 ensured the recognition of JPEG as the web format—at least for photographs. During the 1990s, digital cameras replaced analog ones and, given the limited memory capacities of that era, JPEG became the standard format for photography, especially for consumer-grade cameras.

Read more

Amplify Your Jamstack With Video

By Alex Patterson
Amplify Your Jamstack With Cloudinary Video

As defined by Amazon Web Services (AWS), Amplify is a set of products and tools with which mobile and front-end web developers can build and deploy AWS-powered, secure, and scalable full-stack apps. Also, you can efficiently configure their back ends, connect them to your app with just a few lines of code, and deploy static web apps in only three steps. Historically, because of their performance issues, managing images and videos is a daunting challenge for developers. Even though you can easily load media to an S3 bucket with AWS Amplify, transforming, compressing, and responsively delivering them is labor intensive and time consuming.

Read more
Cloudinary Helps Move James Hardie’s Experience Online

While COVID has affected most businesses, it has been particularly hard on those that sell products for the physical ‘brick and mortar’ world. One company that literally fits that bill is our Australian customer James Hardie, the largest global manufacturer of fibre cement products used in both domestic and commercial construction. These are materials that its buyers ideally want to see up close, in detail. When customers have questions, they expect personal service.

Read more