Detecting Visibility with IntersectionObserver
You'll learn how to trigger actions when an element enters or exits the viewport using a ref and IntersectionObserver.
The Core Problem
Sometimes you need to know when an element becomes visible on screen—for lazy loading images, triggering animations, tracking impressions, or infinite scroll. Constantly checking scroll position is expensive. Instead, use the browser's IntersectionObserver API with a ref to the DOM node.
How It Works
The IntersectionObserver watches a DOM element and fires a callback when it intersects with the viewport (or another container). You create the observer in useEffect, attach it to your ref's DOM node, and clean it up when the component unmounts.
Think of it like a motion detector: you install it (observe), it watches a specific area (your element), and alerts you when something crosses the threshold—without you constantly checking.
The Pattern
function VisibilityTracker() {
const elementRef = useRef(null);
useEffect(() => {
const element = elementRef.current;
if (!element) return;
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
console.log('Element entered viewport!');
} else {
console.log('Element left viewport!');
}
});
});
observer.observe(element);
return () => observer.disconnect();
}, []);
return <div ref={elementRef}>Watch me scroll into view</div>;
}
The observer receives an array of entries. Each entry has isIntersecting (boolean) and other data like intersectionRatio. You must clean up by calling disconnect() in the cleanup function.
Key Takeaway: Use IntersectionObserver with a ref in useEffect to efficiently detect when elements enter or exit the viewport without manual scroll tracking.