JAVASCRIPT

Lazy Load Elements and Detect Visibility with useIntersectionObserver

Utilize the useIntersectionObserver React hook to efficiently detect when a DOM element enters or exits the viewport, enabling lazy loading or scroll-triggered effects.

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

function useIntersectionObserver(options = {}) {
  const { threshold = 0, root = null, rootMargin = '0px' } = options;
  const [entry, setEntry] = useState(null);
  const targetRef = useRef(null);

  useEffect(() => {
    const observer = new IntersectionObserver(([currentEntry]) => {
      setEntry(currentEntry);
    }, { threshold, root, rootMargin });

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

    return () => {
      if (currentTarget) {
        observer.unobserve(currentTarget);
      }
    };
  }, [threshold, root, rootMargin]);

  return [targetRef, entry];
}

export default useIntersectionObserver;
How it works: This useIntersectionObserver hook provides an easy way to observe when a component's target element (referenced via targetRef) intersects with the viewport. It leverages the browser's IntersectionObserver API, returning the targetRef and the latest IntersectionObserverEntry which can be used to implement lazy loading of images or components, infinite scroll, or trigger animations when an element becomes visible, optimizing 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