JAVASCRIPT

Custom useIntersectionObserver Hook for Element Visibility

Create a custom React hook, useIntersectionObserver, to efficiently detect when an element enters or exits the viewport, perfect for lazy loading and scroll animations.

import React, { 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;
    if (currentTarget) {
      observer.observe(currentTarget);
    }

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

  return [targetRef, entry];
}

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

  return (
    <div ref={ref} style={{ minHeight: '200px', background: isVisible ? 'transparent' : '#eee' }}>
      {isVisible ? (
        <img src={src} alt={alt} style={{ maxWidth: '100%' }} />
      ) : (
        <p style={{ textAlign: 'center', padding: '50px' }}>Scroll down to load image...</p>
      )}
    </div>
  );
}

// <LazyLoadImage src="https://via.placeholder.com/400" alt="Placeholder" />
How it works: This custom `useIntersectionObserver` hook provides a simple way to detect when a referenced DOM element enters or exits the viewport. It returns a `ref` to attach to your target element and an `IntersectionObserverEntry` object. The `useEffect` hook initializes and cleans up the observer, updating the `entry` state whenever the target's visibility changes, which can then be used for features like lazy loading images, infinite scrolling, or animating elements when they come into view.

Need help integrating this into your project?

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

Hire DigitalCodeLabs