JAVASCRIPT

React Hook: useIntersectionObserver for Lazy Loading

Create a custom React hook using the Intersection Observer API to detect when an element enters or exits the viewport, ideal for implementing lazy loading, infinite scrolling, or scroll-triggered animations.

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

const useIntersectionObserver = (options) => {
  const [entry, setEntry] = useState(null);
  const [node, setNode] = useState(null);
  const observer = useRef(null);

  useEffect(() => {
    if (observer.current) {
      observer.current.disconnect();
    }

    observer.current = new IntersectionObserver(([ent]) => setEntry(ent), options);

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

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

  return [setNode, entry];
};

export default useIntersectionObserver;
How it works: This `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-like setter for the target element and the latest `IntersectionObserverEntry`. This is commonly used for performance optimizations such as lazy loading images or components, implementing 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