JAVASCRIPT
React `useIntersectionObserver` for Element Visibility Detection
Implement lazy loading and infinite scrolling efficiently with `useIntersectionObserver`, a React hook that detects when a target element enters or exits the viewport.
import { useRef, useState, useEffect } from 'react';
const useIntersectionObserver = (options) => {
const [entry, setEntry] = useState(null);
const [node, setNode] = useState(null); // Ref to the DOM element
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]); // Re-observe if node or options change
return [setNode, entry];
};
How it works: This `useIntersectionObserver` hook provides a convenient way to observe when a DOM element enters or exits the viewport. It returns a function `setNode` to attach to the target element and the `entry` object containing intersection details. This is highly useful for implementing performance optimizations like lazy loading images or components, infinite scrolling, or triggering animations when an element becomes visible.