JAVASCRIPT
Implement Lazy Loading and Scroll Effects with useIntersectionObserver Hook
Discover how to build a `useIntersectionObserver` React hook to detect when an element enters or exits the viewport, perfect 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 [node, setNode] = useState(null); // Element to observe
const observer = useRef(null); // Persistent ref for the IntersectionObserver instance
useEffect(() => {
// Disconnect previous observer if node or options change
if (observer.current) {
observer.current.disconnect();
}
// Create new observer only if a node is provided
if (node) {
observer.current = new IntersectionObserver(([ent]) => setEntry(ent), options);
observer.current.observe(node);
}
// Cleanup: disconnect observer when component unmounts or dependencies change
return () => {
if (observer.current) {
observer.current.disconnect();
}
};
}, [node, options]); // Re-run if node or options object changes
return [setNode, entry]; // Returns a setter for the element and the observation entry
}
// Example Usage:
/*
import React from 'react';
function LazyImage({ src, alt }) {
const [setRef, entry] = useIntersectionObserver({ threshold: 0.1 });
const isVisible = entry?.isIntersecting;
return (
<img
ref={setRef} // Assign the ref using the setter
src={isVisible ? src : ''} // Only load src if visible
alt={alt}
style={{ minHeight: '200px', width: '100%', backgroundColor: '#eee' }} // Placeholder style
/>
);
}
*/
How it works: The `useIntersectionObserver` hook leverages the browser's Intersection Observer API to detect when a target element enters or exits the viewport, or crosses a specified threshold. It returns a setter function to assign the element to observe and the `IntersectionObserverEntry` object. This is immensely useful for implementing features like lazy loading images, infinite scrolling, triggering animations when elements come into view, or tracking element visibility analytics without relying on scroll events.