JAVASCRIPT
useIntersectionObserver for scroll-based effects
A flexible React hook to detect when an element enters or exits the viewport, perfect for lazy loading, infinite scrolling, or scroll animations.
import { useRef, useEffect, useState } from 'react';
function useIntersectionObserver(options) {
const [entry, setEntry] = useState(null);
const observerRef = useRef(); // Ref for the DOM element to observe
useEffect(() => {
const node = observerRef.current; // Target DOM element
const hasIOSupport = !!window.IntersectionObserver; // Check browser support
if (!hasIOSupport || !node) return; // Exit if no support or no element
const observer = new IntersectionObserver(([entry]) => setEntry(entry), options);
observer.observe(node);
return () => observer.disconnect(); // Cleanup observer on unmount
}, [observerRef, options]); // Re-run if ref or options change
return [observerRef, entry];
}
// Example Usage:
// function LazyImage({ src, alt }) {
// const [imgRef, entry] = useIntersectionObserver({
// threshold: 0.1,
// rootMargin: '0px',
// });
// const isVisible = entry?.isIntersecting;
// return (
// <img
// ref={imgRef}
// src={isVisible ? src : undefined}
// alt={alt}
// style={{ minHeight: '200px', background: '#ccc' }}
// />
// );
// }
How it works: The `useIntersectionObserver` hook simplifies the use of the browser's `IntersectionObserver` API in React. It takes an `options` object for the observer and returns a ref to attach to the target element, along with the latest `IntersectionObserverEntry`. This allows components to react when an element enters or exits the viewport, making it ideal for implementing features like lazy loading images, infinite scrolling, or triggering animations when elements become visible, improving performance and user experience.