Skip to content

Lazy-Load React and Boost 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:

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.

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.

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>;

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:

class Greeting extends React.Component {
  render(){
    return <h1>Hi, I’m a class component!</h1>;
  }
}
Code language: JavaScript (javascript)

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

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

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 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.

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:

export default Login;
export const abc = className; **Not Valid **
Code language: JavaScript (javascript)

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.

const Login = React.lazy(() => import(‘./Components/Login’));
Code language: JavaScript (javascript)

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.

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:

<Image 
  public-id="sample" 
  loading="lazy"
  width="400"
  height="300">
</Image>
Code language: HTML, XML (xml)

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.

Back to top

Featured Post