In the world of web and mobile app development, performance is key. As users, we expect apps to load instantly with smooth scrolling and seamless interactions.

As developers, delivering this high-quality experience can be challenging. Images, videos, ads, and other external resources can significantly slow down initial load times and create lag when scrolling. This is where the power of React lazy loading comes into play.

Lazy loading is a technique to defer loading non-essential components and assets until the user scrolls to where they are needed in the viewport. Implementing lazy loading techniques properly can lead to vast improvements in perceived performance optimization, loading times, and overall user experience.

In this post, let’s explore React lazy loading in depth – from what it is and why it matters to practical implementation tips.

What is Lazy Loading?

Lazy loading means delaying the loading of assets, code, modules, components, or anything else on a web page until it is needed.

Instead of loading everything upfront on initial page load, you can strategically load non-essential items later when they are about to come into view.

For example, images below the fold could be lazy loaded only when the user scrolls to that section. Same for components that aren’t immediately visible.

This approach offers three major benefits:

  1. Faster initial page load time – Less assets need to download on first paint, so the page loads faster.
  2. Reduced memory usage – With less to load upfront, memory usage stays lower.
  3. Smoother scrolling – Loading items as needed prevents lag when scrolling down long pages.

So rather than optimizing what to load, lazy loading focuses on when to load for best user experience.

Why use React Lazy Loading?

React applications tend to have a lot going on – multiple components, images, videos, ads, etc. Without optimization, this can lead to:

  • Poor initial load performance
  • Memory overload
  • Janky scrolling

By React lazy loading effectively, you can avoid these pitfalls to deliver high-performance React apps at scale.

Specifically for React, lazy loading aligns perfectly with its code splitting and suspense capabilities for loading parts of an app when needed.

Let’s look at some specific React lazy loading techniques.

How to Lazy Load Components

1. React.lazy and Suspense

The simplest way to lazy load components in React is using:

  1. React.lazy to create a lazy-loaded component
  2. Suspense to specify loading behavior

Here is an example:

import React, { Suspense } from 'react';

const LazyComponent = React.lazy(() => import('./LazyComponent'));

function MyComponent() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <LazyComponent />
      </Suspense>
    </div>
  );
}

Breaking this down:

  • React.lazy takes a callback function that calls dynamic import() to load the LazyComponent module
  • This component is now considered lazy loaded
  • We then render LazyComponent inside a Suspense component
  • Suspense lets us show some fallback loading UI like a spinner while the lazy component loads

And that’s the basics of leveraging built-in lazy load capabilities!

2. react-loadable

For more advanced React lazy loading, check out react-loadable.

Benefits include:

  • Easier dynamic importing
  • Flexible loading behavior
  • Error handling capabilities
  • SSR friendly options

Example:

import Loadable from 'react-loadable';

const LazyComponent = Loadable({
  loader: () => import('./LazyComponent'),
  loading: () => <div>Loading...</div>,
});

function MyComponent() {
  return <LazyComponent />; 
}

As we can see, react-loadable provides nice abstractions over React.lazy while offering more extensibility for advanced use cases.

3. React Router Config Loading

When dealing with React Router:

Lazy load route component on demand versus upfront:

const Route = ReactRouterDOM.Route;
const LazyComponent = React.lazy(() => import('./components/LazyComponent'));

function MyComponent() {

  return (
    <Suspense fallback={<div>Loading...</div>}>
      <Route path="/lazy" component={LazyComponent}/> 
    </Suspense>
  );
}

How to Lazy Load Images

Images often account for most of a web page’s initial load time.

Lazy loading them can speed up first paint tremendously. Here are some approaches.

1. Native Lazy Loading

Modern browsers support native image lazy loading through the loading attribute:

<img src="image.png" loading="lazy" />

This automatically defers offscreen images without JavaScript!

However, no fallback is handled if the browser doesn’t support it.

2. react-lazyload

For wider compatibility, use a library like react-lazyload:

import { LazyLoadImage } from 'react-lazyload';

<LazyLoadImage
  src="image.png"
  placeholder={<Placeholder />}
/>

Benefits include placeholder and fallback support!

3. More Image Optimization

Along with lazy loading, further optimize images by:

  • Choosing efficient formats (WebP, AVIF)
  • Generating multiple sizes for responsive devices
  • Compressing with tools like TinyPNG

Every little bit counts for performance optimization.

How to Lazy Load Other Assets

The concepts can apply to lazy loading anything – ads, videos, file imports, etc.

Some options:

  • Design a custom React Suspense component for the asset
  • Use helpers like React Helmet Async to delay loading scripts
  • Create container components that dynamically import when visible

Get creative with various techniques to lazily load whatever you can afford to.

Performance optimization Benefits

Applying even basic React lazy loading techniques can dramatically improve user experience.

Some measured examples across react-lazyload sites:

  • 61% faster initial load
  • 44% lower data consumption
  • 42% faster time-to-interactive

Beyond the numbers, users will notice and appreciate the snappiness!

Conclusion & Next Steps

By selectively React lazy loading components, images, and other assets, we can optimize React app loading times.

Less to download upfront means faster first paints, less memory usage, and smoother scrolling as users navigate through your app.

Now that you know what React lazy loading is and how to implement it, try incorporating some techniques like code splitting into your next project for big performance wins.

Every little bit makes a difference!

And if you have an existing React codebase suffering from performance pains or need help building a new high-scale React application, reach out to me.

As an expert React developer, I can assess your current app performance and provide recommendations to lazy load your way to lightning fast experiences.