JAVASCRIPT

Creating useIntersectionObserver for Lazy Loading and Visibility Detection

Implement lazy loading, infinite scroll, or element visibility detection in React with a custom `useIntersectionObserver` hook for optimal performance.

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

function 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 () => {
      observer.current.disconnect();
    };
  }, [node, options]);

  return [setNode, entry];
}

// Example Usage:
function LazyImage({ src, alt }) {
  const [setRef, entry] = useIntersectionObserver({ threshold: 0.1 });
  const isVisible = entry?.isIntersecting;

  return (
    <img
      ref={setRef}
      src={isVisible ? src : 'placeholder.jpg'}
      alt={alt}
      style={{ minHeight: '200px', backgroundColor: '#eee' }}
    />
  );
}
How it works: The `useIntersectionObserver` hook provides an easy way to detect when an element enters or exits the viewport. It initializes an `IntersectionObserver` instance and observes a provided DOM node. The hook returns a function to set the target node and the latest `IntersectionObserverEntry`, allowing components to react to visibility changes for features like lazy loading or infinite scrolling.

Need help integrating this into your project?

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

Hire DigitalCodeLabs