Published on

useIntersectionObserver Hooks

useIntersectionObserver Hooks

useIntersectionObserver Hooks

useIntersectionObserver Code and Usage

useIntersectionObserver is a hook to observe when an element enters or exits the viewport.

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

const useIntersectionObserver = (callback, options) => {
  const targetRef = useRef();
  const [isIntersecting, setIsIntersecting] = useState(false);

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries.length > 0) {
          setIsIntersecting(entries[0].isIntersecting);
          if (callback) {
            callback(entries[0]);
          }
        }
      },
      { ...options }
    );

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

    return () => {
      if (targetRef.current) {
        observer.unobserve(targetRef.current);
      }
    };
  }, [callback, options]);

  return { targetRef, isIntersecting };
};

// Usage
const IntersectionObserverExample = () => {
  const handleIntersection = (entry) => {
    console.log("Element is intersecting:", entry.isIntersecting);
  };

  const observerOptions = {
    root: null,
    rootMargin: "0px",
    threshold: 0.5,
  };

  const { targetRef, isIntersecting } = useIntersectionObserver(
    handleIntersection,
    observerOptions
  );

  return (
    <div>
      <div
        ref={targetRef}
        style={{
          width: "100px",
          height: "100px",
          background: "lightgray",
          margin: "200px auto",
        }}
      >
        Intersection Observer Target
      </div>
      {isIntersecting ? (
        <p>Element is intersecting!</p>
      ) : (
        <p>Element is not intersecting.</p>
      )}
    </div>
  );
};

Previous Article

Next Article