JAVASCRIPT

Custom Hook: useIntersectionObserver for Lazy Loading/Visibility

Implement a custom React hook, useIntersectionObserver, to efficiently detect when an element enters or exits the viewport, enabling lazy loading or animations.

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

function useIntersectionObserver(options) {
  const [isIntersecting, setIntersecting] = useState(false);
  const ref = useRef(null);

  useEffect(() => {
    const observer = new IntersectionObserver(([entry]) => {
      setIntersecting(entry.isIntersecting);
    }, options);

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

    return () => {
      if (ref.current) {
        observer.unobserve(ref.current);
      }
    };
  }, [ref, options]);

  return [ref, isIntersecting];
}

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

//   return (
//     <img
//       ref={imgRef}
//       src={isVisible ? src : 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='} // Placeholder
//       alt={alt}
//       style={{ minHeight: '100px', backgroundColor: '#eee' }}
//     />
//   );
// }
How it works: The `useIntersectionObserver` hook provides a way to observe changes in the intersection of a target element with an ancestor element or with the top-level document's viewport. It returns a ref to attach to your target element and a boolean `isIntersecting` indicating whether the element is currently visible. This is crucial for performance optimizations like lazy loading images, implementing 'infinite scroll', or triggering animations when elements enter the viewport.

Need help integrating this into your project?

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

Hire DigitalCodeLabs