← Back to all snippets
JAVASCRIPT

Detect Element Visibility with Intersection Observer

Easily detect when a React element enters or exits the viewport using the Intersection Observer API, enabling lazy loading, infinite scrolling, and "in-view" animations.

import { useRef, useState, useEffect } from 'react';

function useIntersectionObserver(options) {
  const [entry, setEntry] = useState(null);
  const [node, setNode] = useState(null); // Element to observe

  const observer = useRef(null);

  useEffect(() => {
    if (observer.current) {
      observer.current.disconnect();
    }

    observer.current = new IntersectionObserver(([ent]) => setEntry(ent), options);

    if (node) {
      observer.current.observe(node);
    }

    return () => {
      if (observer.current) {
        observer.current.disconnect();
      }
    };
  }, [node, options]); // Re-run if node or options change

  return [setNode, entry]; // Returns setter for the ref and the observer entry
}

// Example Usage:
// function LazyImage({ src, alt }) {
//   const [setNode, entry] = useIntersectionObserver({ threshold: 0.1 });
//   const isVisible = entry?.isIntersecting;

//   return (
//     <img
//       ref={setNode}
//       src={isVisible ? src : 'placeholder.jpg'} // Replace with a low-res placeholder
//       alt={alt}
//       style={{ minHeight: '200px', backgroundColor: '#eee' }} // Example styling
//     />
//   );
// }
How it works: The `useIntersectionObserver` hook provides a way to observe when a DOM element enters or exits the viewport. It leverages the browser's native Intersection Observer API. The hook returns a setter function (`setNode`) to assign the element you want to observe, and an `entry` object containing information about the intersection (like `isIntersecting`). This is highly useful for implementing features such as lazy loading images, infinite scrolling, or triggering animations when an element scrolls into view, optimizing performance by only loading or rendering content when it's visible to the user.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs