JAVASCRIPT
React useIntersectionObserver Hook for Element Visibility
Utilize a custom React hook to detect when an element enters or exits the viewport, perfect for lazy loading images, infinite scrolling, or tracking visibility.
import { useRef, useEffect, useState } from 'react';
function useIntersectionObserver(options) {
const [entry, setEntry] = useState(null);
const targetRef = useRef(null);
useEffect(() => {
const target = targetRef.current;
if (!target) return;
const observer = new IntersectionObserver(([ent]) => {
setEntry(ent);
}, options);
observer.observe(target);
return () => {
observer.unobserve(target);
};
}, [options]);
return [targetRef, entry];
}
How it works: The useIntersectionObserver hook leverages the browser's `IntersectionObserver` API to monitor the visibility of a DOM element. It returns a `targetRef` to attach to the element you want to observe and an `entry` object containing information about its intersection status. This hook is invaluable for implementing features like lazy loading images, infinite scrolling, or triggering animations when elements come into view, making UI more efficient and dynamic.