or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-react-lazyload

React component for lazy loading that improves performance by loading content only when it enters the viewport.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/react-lazyload@3.2.x

To install, run

npx @tessl/cli install tessl/npm-react-lazyload@3.2.0

index.mddocs/

React LazyLoad

React LazyLoad is a high-performance React component for lazy loading that improves application performance by loading content only when it enters the viewport. It provides efficient viewport detection using only two global event listeners regardless of the number of lazy-loaded components, supports both one-time and continuous lazy loading modes, offers configurable offset values for preloading elements before they become visible, includes throttling and debouncing for scroll events, and provides decorator syntax for easy integration with existing components.

Package Information

  • Package Name: react-lazyload
  • Package Type: npm
  • Language: JavaScript (React component library)
  • Installation: npm install react-lazyload

Core Imports

import LazyLoad from 'react-lazyload';

For decorator support:

import LazyLoad, { lazyload } from 'react-lazyload';

For utility functions:

import LazyLoad, { forceCheck, forceVisible } from 'react-lazyload';

CommonJS:

const LazyLoad = require('react-lazyload');
const { lazyload, forceCheck, forceVisible } = require('react-lazyload');

Basic Usage

import React from 'react';
import LazyLoad from 'react-lazyload';

const App = () => {
  return (
    <div className="list">
      {/* Basic lazy loading */}
      <LazyLoad height={200}>
        <img src="image1.jpg" alt="Lazy loaded image" />
      </LazyLoad>

      {/* One-time lazy loading */}
      <LazyLoad height={200} once>
        <MyComponent />
      </LazyLoad>

      {/* Preload when 100px from viewport */}
      <LazyLoad height={200} offset={100}>
        <MyComponent />
      </LazyLoad>

      {/* With custom placeholder */}
      <LazyLoad height={200} placeholder={<div>Loading...</div>}>
        <MyComponent />
      </LazyLoad>
    </div>
  );
};

Architecture

React LazyLoad is built around several key components:

  • LazyLoad Component: The main wrapper component that handles visibility detection and content rendering
  • Global Event Management: Uses only two global event listeners (scroll/resize) for all LazyLoad instances for optimal performance
  • Viewport Detection: Efficient algorithms for detecting when elements enter/exit the viewport, including support for overflow containers
  • Decorator Pattern: Higher-order component decorator for seamless integration with existing components
  • Manual Control: Utility functions for programmatic control over lazy loading behavior

Capabilities

LazyLoad Component

The main React component that wraps content and loads it only when visible in the viewport.

/**
 * LazyLoad wrapper component for lazy loading content
 * @param {React.ComponentProps<typeof LazyLoad>} props - Component props
 * @returns {React.ReactElement} LazyLoad wrapper element
 */
function LazyLoad(props: LazyLoadProps): React.ReactElement;

interface LazyLoadProps {
  /** The content to lazy load (only one child allowed) */
  children: React.ReactNode;
  /** Placeholder height for initial render, can be number or string like '100%' */
  height?: number | string;
  /** Whether to stop observing after first load */
  once?: boolean;
  /** Viewport offset for triggering load, number or [horizontal, vertical] array */
  offset?: number | [number, number];
  /** Whether component is in overflow container */
  overflow?: boolean;
  /** Whether to listen to resize events */
  resize?: boolean;
  /** Whether to listen to scroll events */
  scroll?: boolean;
  /** Throttle delay for scroll/resize handlers in milliseconds */
  throttle?: number | boolean;
  /** Debounce delay for scroll/resize handlers in milliseconds */
  debounce?: number | boolean;
  /** Custom placeholder element to show before loading */
  placeholder?: React.ReactNode;
  /** Custom scroll container selector string or DOM element */
  scrollContainer?: string | HTMLElement;
  /** Whether to unmount when not visible */
  unmountIfInvisible?: boolean;
  /** CSS class for wrapper element */
  className?: string;
  /** Prefix for generated CSS classes */
  classNamePrefix?: string;
  /** Inline styles for wrapper element */
  style?: React.CSSProperties;
}

Default Props:

  • className: ''
  • classNamePrefix: 'lazyload'
  • once: false
  • offset: 0
  • overflow: false
  • resize: false
  • scroll: true
  • unmountIfInvisible: false

Usage Examples:

// Basic image lazy loading
<LazyLoad height={200}>
  <img src="tiger.jpg" alt="Tiger" />
</LazyLoad>

// One-time loading with offset
<LazyLoad height={200} once offset={100}>
  <ExpensiveComponent />
</LazyLoad>

// Overflow container support
<LazyLoad overflow>
  <div>Content in scrollable container</div>
</LazyLoad>

// Custom placeholder
<LazyLoad placeholder={<div className="spinner">Loading...</div>}>
  <MyComponent />
</LazyLoad>

// Performance optimization with debouncing
<LazyLoad debounce={300}>
  <HeavyComponent />
</LazyLoad>

Decorator Function

Higher-order component decorator that wraps components with LazyLoad functionality.

/**
 * Decorator function for lazy loading components
 * @param {LazyLoadProps} options - LazyLoad options to apply
 * @returns {function} Higher-order component function
 */
function lazyload(options?: Partial<LazyLoadProps>): (WrappedComponent: React.ComponentType) => React.ComponentType;

Usage Examples:

import { lazyload } from 'react-lazyload';

// ES6 decorator syntax
@lazyload({
  height: 200,
  once: true,
  offset: 100
})
class MyComponent extends React.Component {
  render() {
    return <div>This component is lazyloaded by default!</div>;
  }
}

// Function syntax
const LazyMyComponent = lazyload({
  height: 200,
  once: true
})(MyComponent);

Manual Visibility Control

forceCheck

Manually triggers visibility checking for all registered LazyLoad components.

/**
 * Forces a visibility check for all LazyLoad components
 * Useful when components enter viewport without scroll/resize events
 */
function forceCheck(): void;

Usage Examples:

import { forceCheck } from 'react-lazyload';

// After showing a hidden container
const showModal = () => {
  setModalVisible(true);
  // Force check since components became visible without scroll
  forceCheck();
};

// After dynamic content insertion
const addContent = () => {
  setItems([...items, newItem]);
  setTimeout(forceCheck, 0); // Check after DOM update
};

forceVisible

Forces all LazyLoad components to display regardless of viewport visibility.

/**
 * Forces all LazyLoad components to display regardless of visibility
 * Useful for printing or full content display
 */
function forceVisible(): void;

Usage Examples:

import { forceVisible } from 'react-lazyload';

// Before printing
const handlePrint = () => {
  forceVisible(); // Load all content for printing
  setTimeout(() => window.print(), 100);
};

// For accessibility or full content display
const showAllContent = () => {
  forceVisible();
  setShowAllMode(true);
};

Advanced Usage Patterns

Overflow Container Support

For lazy loading within scrollable containers:

// CSS: Ensure container has position other than static
.scroll-container {
  height: 400px;
  overflow-y: auto;
  position: relative; /* Required for overflow detection */
}

// React component
<div className="scroll-container">
  <LazyLoad height={200} overflow>
    <MyComponent />
  </LazyLoad>
</div>

Performance Optimization

// Throttle scroll events (limits to every 300ms)
<LazyLoad throttle={300}>
  <MyComponent />
</LazyLoad>

// Debounce scroll events (waits 300ms after scroll stops)
<LazyLoad debounce={300}>
  <MyComponent />
</LazyLoad>

// Use boolean for default timing (300ms)
<LazyLoad throttle>
  <MyComponent />
</LazyLoad>

Custom Scroll Container

// String selector
<LazyLoad scrollContainer=".custom-scroll">
  <MyComponent />
</LazyLoad>

// DOM element reference
const scrollElement = useRef();
<LazyLoad scrollContainer={scrollElement.current}>
  <MyComponent />
</LazyLoad>

Offset Configuration

// Single number applies to all directions
<LazyLoad offset={100}>  {/* 100px offset in all directions */}
  <MyComponent />
</LazyLoad>

// Array format: [horizontal, vertical]
<LazyLoad offset={[50, 100]}>  {/* 50px horizontal, 100px vertical */}
  <MyComponent />
</LazyLoad>

// Negative offset delays loading
<LazyLoad offset={-50}>  {/* Load 50px after entering viewport */}
  <MyComponent />
</LazyLoad>

Unmounting Invisible Content

// Unmount component when not visible (saves memory)
<LazyLoad unmountIfInvisible>
  <ExpensiveComponent />
</LazyLoad>

Error Handling

React LazyLoad handles errors gracefully:

  • Invalid DOM elements: Safely handles cases where refs don't point to HTML elements
  • getBoundingClientRect errors: Falls back to default positioning when DOM methods fail
  • Event listener failures: Degrades gracefully when passive events aren't supported

Browser Compatibility

  • Modern browsers: Full support with passive event listeners for optimal performance
  • Legacy browsers: Automatic fallback to standard event listeners
  • Server-side rendering: Safe to use with SSR, gracefully handles missing window object
  • Internet Explorer: Compatible with proper polyfills for getBoundingClientRect

Performance Characteristics

  • Memory efficient: Only 2 global event listeners regardless of component count
  • CPU optimized: Efficient viewport detection algorithms
  • Network friendly: Loads content only when needed
  • Scroll performance: Uses passive events and optional throttling/debouncing
  • Cleanup: Automatic listener removal on component unmount