JAVASCRIPT
Custom React Hook for Element Visibility Detection
A React hook leveraging the Intersection Observer API to detect when an element enters or exits the viewport. Ideal for lazy loading images, infinite scrolling, or scroll-triggered animations.
import { useRef, useEffect, useState } from 'react';
function useIntersectionObserver(options) {
const [entry, setEntry] = useState(null);
const targetRef = useRef(null);
useEffect(() => {
if (!targetRef.current) return;
const observer = new IntersectionObserver(([entry]) => {
setEntry(entry);
}, options);
observer.observe(targetRef.current);
return () => {
if (targetRef.current) {
observer.unobserve(targetRef.current);
}
};
}, [targetRef.current, options]); // Re-run if target or options change
return [targetRef, entry];
// Example Usage:
// function LazyImage({ src, alt }) {
// const [targetRef, entry] = useIntersectionObserver({ threshold: 0.1 });
// const isVisible = entry?.isIntersecting;
//
// return (
// <img
// ref={targetRef}
// src={isVisible ? src : 'placeholder.jpg'} // Replace with a real placeholder
// alt={alt}
// style={{ minHeight: '200px', background: '#f0f0f0' }} // Placeholder style
// />
// );
// }
How it works: The `useIntersectionObserver` hook provides a way to detect when a target element enters or exits the browser's viewport. It returns a `ref` to be attached to the target element and an `entry` object containing intersection details. Internally, it uses the browser's `IntersectionObserver` API. When the component mounts, it observes the target element and updates the `entry` state when intersection changes occur. On unmount, it cleans up the observer. This is highly efficient for implementing features like lazy loading or "in-view" animations.