JAVASCRIPT

Implement useIntersectionObserver for Lazy Loading & Visibility

Create a custom React hook to efficiently detect when a DOM element enters or exits the viewport, ideal for lazy loading images/components or animations.

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

function useIntersectionObserver(options) {
  const [entry, setEntry] = useState(null);
  const [node, setNode] = useState(null); // The DOM node we want to observe

  const observer = useRef(null);

  useEffect(() => {
    // Make sure we have a node to observe and a browser environment
    if (typeof window === 'undefined' || !window.IntersectionObserver || !node) {
      return;
    }

    // Disconnect previous observer if node or options change
    if (observer.current) {
      observer.current.disconnect();
    }

    observer.current = new IntersectionObserver(([currentEntry]) => {
      setEntry(currentEntry);
    }, options);

    observer.current.observe(node);

    return () => {
      observer.current.disconnect();
    };
  }, [node, options]); // Re-create observer if node or options change

  return [setNode, entry];
}
How it works: The `useIntersectionObserver` hook provides a way to detect when a DOM element enters or exits the viewport. It leverages the browser's `IntersectionObserver` API, efficiently avoiding expensive scroll event listeners. The hook returns a function to set the DOM `node` to observe and the `entry` object from the observer, which contains information like `isIntersecting`. It's perfect for implementing lazy loading of images or components, infinite scrolling, or triggering animations when an element becomes visible, significantly improving page performance.

Need help integrating this into your project?

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

Hire DigitalCodeLabs