JAVASCRIPT
Lazy Loading with useIntersectionObserver React Hook
Implement a `useIntersectionObserver` React hook for efficient lazy loading of images or components, detecting when an element enters the viewport for performance optimization.
import { useRef, useEffect, useState } from 'react';
function useIntersectionObserver(options) {
const [isIntersecting, setIsIntersecting] = useState(false);
const elementRef = useRef(null);
useEffect(() => {
const observer = new IntersectionObserver(([entry]) => {
setIsIntersecting(entry.isIntersecting);
}, options);
if (elementRef.current) {
observer.observe(elementRef.current);
}
return () => {
if (elementRef.current) {
observer.unobserve(elementRef.current);
}
};
}, [options]); // Re-run if options change
return [elementRef, isIntersecting];
}
// Example Usage:
// function LazyImage({ src, alt }) {
// const [imgRef, isVisible] = useIntersectionObserver({
// threshold: 0.1, // Trigger when 10% of element is visible
// rootMargin: '0px'
// });
// return (
// <img
// ref={imgRef}
// src={isVisible ? src : 'placeholder.gif'} // Use a placeholder until visible
// alt={alt}
// style={{ minHeight: '200px', background: '#eee' }}
// />
// );
// }
How it works: The `useIntersectionObserver` hook provides a powerful way to detect when a React component or any DOM element enters or exits the viewport. It leverages the browser's `IntersectionObserver` API. You pass `options` (like `threshold` or `rootMargin`) to customize when the observer's callback should fire. The hook returns a `ref` that you attach to the target element and a boolean `isIntersecting` state. This is highly valuable for implementing lazy loading of images, videos, or components, or triggering animations when elements become visible, thereby optimizing page performance and user experience.