JAVASCRIPT

Implement Lazy Loading with useIntersectionObserver Hook

Build a React useIntersectionObserver hook to efficiently detect when an element enters or leaves the viewport, enabling lazy loading or scroll-based animations.

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

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

  useEffect(() => {
    const node = elementRef.current; // DOM element to observe
    if (!node) return;

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

    observer.observe(node);
    observerRef.current = observer; // Store observer to disconnect

    return () => {
      if (observerRef.current) {
        observerRef.current.disconnect();
      }
    };
  }, [JSON.stringify(options)]); // Recreate observer if options change, deep equality for options object

  return [elementRef, entry];
}

// Example Usage:
// function LazyImage({ src, alt }) {
//   const [imgRef, entry] = useIntersectionObserver({
//     root: null, // viewport
//     rootMargin: '0px',
//     threshold: 0.1 // 10% visible
//   });
//   const isVisible = entry?.isIntersecting;

//   return (
//     <img
//       ref={imgRef}
//       src={isVisible ? src : 'placeholder.jpg'} // Load actual image only when visible
//       alt={alt}
//       style={{ minHeight: '200px', backgroundColor: '#eee' }} // Placeholder style
//     />
//   );
// }
How it works: The `useIntersectionObserver` hook provides a declarative way to detect when a target element enters or exits the viewport. It utilizes the browser's `IntersectionObserver` API. The hook returns a ref (`elementRef`) that should be attached to the DOM element you want to observe, and an `entry` object containing details about the intersection. This is highly valuable for implementing features like lazy loading images, infinite scrolling, or triggering animations when elements become visible, significantly improving performance and user experience.

Need help integrating this into your project?

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

Hire DigitalCodeLabs