React component for lazy loading that improves performance by loading content only when it enters the viewport.
npx @tessl/cli install tessl/npm-react-lazyload@3.2.0React 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.
npm install react-lazyloadimport 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');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>
);
};React LazyLoad is built around several key components:
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: falseoffset: 0overflow: falseresize: falsescroll: trueunmountIfInvisible: falseUsage 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>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);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
};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);
};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>// 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>// String selector
<LazyLoad scrollContainer=".custom-scroll">
<MyComponent />
</LazyLoad>
// DOM element reference
const scrollElement = useRef();
<LazyLoad scrollContainer={scrollElement.current}>
<MyComponent />
</LazyLoad>// 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>// Unmount component when not visible (saves memory)
<LazyLoad unmountIfInvisible>
<ExpensiveComponent />
</LazyLoad>React LazyLoad handles errors gracefully: