JAVASCRIPT

Lazy Loading and Visibility Detection with useIntersectionObserver Hook

Efficiently detect when an element enters or exits the viewport using the `IntersectionObserver` API wrapped in a custom React hook for lazy loading images or infinite scrolling.

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

function useIntersectionObserver(options) {
  const [entry, setEntry] = useState(null);
  const targetRef = useRef(null);

  useEffect(() => {
    const observer = new IntersectionObserver(([ent]) => {
      setEntry(ent);
    }, options);

    const currentTarget = targetRef.current;
    if (currentTarget) {
      observer.observe(currentTarget);
    }

    return () => {
      if (currentTarget) {
        observer.unobserve(currentTarget);
      }
    };
  }, [options]); // Re-create observer if options change

  return [targetRef, entry];
}

// Example Usage:
// function LazyImage({ src, alt }) {
//   const [ref, entry] = useIntersectionObserver({
//     threshold: 0.1, // Trigger when 10% of element is visible
//     rootMargin: '0px'
//   });
//   const isVisible = entry?.isIntersecting;

//   return (
//     <img
//       ref={ref}
//       src={isVisible ? src : 'placeholder.jpg'} // Use a placeholder until visible
//       alt={alt}
//       style={{ minHeight: '200px', background: '#f0f0f0' }} // Placeholder style
//     />
//   );
// }
How it works: The `useIntersectionObserver` hook provides a clean interface to the browser's `IntersectionObserver` API. It allows you to monitor changes in the intersection of a target element with an ancestor scroll container or the viewport. The hook returns a `ref` that you attach to the target element and an `entry` object containing intersection details. This is highly valuable for implementing lazy loading of images or components, infinite scrolling, or triggering animations when elements become visible.

Need help integrating this into your project?

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

Hire DigitalCodeLabs