JAVASCRIPT

React useIntersectionObserver for Lazy Loading & Visibility

Efficiently detect when a React component enters or leaves the viewport using the `useIntersectionObserver` hook, ideal for lazy loading images or infinite scrolling.

import { useRef, useState, useEffect } 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; // Store current ref

    if (currentTarget) {
      observer.observe(currentTarget);
    }

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

  return [targetRef, entry];
}
How it works: The `useIntersectionObserver` hook provides a way to monitor the visibility of a DOM element relative to its ancestor or the viewport. It returns a `ref` to attach to the target element and the `IntersectionObserverEntry` which describes its intersection status. This is perfect for implementing features like lazy loading images, infinite scrolling, tracking ad visibility, or triggering animations when elements come into view, improving application 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