JAVASCRIPT
Detecting Element Visibility with useIntersectionObserver Hook
A React hook `useIntersectionObserver` to easily detect when a DOM element enters or exits the viewport, perfect for lazy loading and animations.
import { useRef, useState, useEffect } from 'react';
function useIntersectionObserver(options) {
const [entry, setEntry] = useState(null);
const targetRef = useRef(null);
useEffect(() => {
const node = targetRef.current;
if (!node) return;
const observer = new IntersectionObserver(([ent]) => {
setEntry(ent);
}, options);
observer.observe(node);
return () => {
observer.disconnect();
};
}, [options]); // Re-run if options change, though usually static
return [targetRef, entry];
}
// Example Usage:
// function LazyImage({ src, alt }) {
// const [targetRef, entry] = useIntersectionObserver({
// root: null, // viewport
// rootMargin: '0px',
// threshold: 0.1, // trigger when 10% of element is visible
// });
// const isVisible = entry?.isIntersecting;
//
// return (
// <img
// ref={targetRef}
// src={isVisible ? src : 'placeholder.jpg'} // Load actual image only when visible
// alt={alt}
// style={{ minHeight: '200px', backgroundColor: '#eee' }}
// />
// );
// }
How it works: The `useIntersectionObserver` hook provides a clean way to use the Intersection Observer API in React. It takes an `options` object for the observer and returns a `ref` to attach to the target element and an `entry` object containing intersection details. The `useEffect` hook initializes the observer, attaching it to the `targetRef` element. When the element's visibility changes according to the specified options, the `setEntry` callback updates the state, allowing components to react to visibility changes (e.g., for lazy loading images or triggering animations).