JAVASCRIPT
Lazy Load Elements with useIntersectionObserver Hook
Implement a React `useIntersectionObserver` hook for efficient lazy loading, infinite scrolling, or detecting when an element enters or exits the viewport.
import { useRef, useState, useEffect } from 'react';
function useIntersectionObserver(options) {
const [entry, setEntry] = useState({});
const [node, setNode] = useState(null);
const observer = useRef(null);
useEffect(() => {
if (observer.current) {
observer.current.disconnect();
}
observer.current = new IntersectionObserver(([ent]) => setEntry(ent), options);
if (node) {
observer.current.observe(node);
}
return () => {
if (observer.current) {
observer.current.disconnect();
}
};
}, [node, options]);
return [setNode, entry];
}
// Example Usage:
// function ImageLoader({ src, alt }) {
// const [setRef, entry] = useIntersectionObserver({ threshold: 0.1 });
// const isVisible = entry.isIntersecting;
// return (
// <img
// ref={setRef}
// src={isVisible ? src : 'placeholder.jpg'} // Replace with a low-res placeholder
// alt={alt}
// style={{ minHeight: '200px', backgroundColor: '#eee' }} // Ensure element has height
// />
// );
// }
How it works: The `useIntersectionObserver` hook leverages the browser's Intersection Observer API to detect when a referenced DOM element enters or exits the viewport. It provides the `IntersectionObserverEntry` object, allowing developers to implement features like lazy loading images, infinite scrolling, or triggering animations when elements become visible, improving performance by deferring operations until necessary. The hook returns a ref setter and the current intersection entry.