A React hook that tracks whether an element is visible in the viewport using the IntersectionObserver API.

This hook observes a DOM element through the IntersectionObserver API and returns a boolean indicating whether the element is currently visible (i.e., intersecting with the viewport). The hook updates automatically when the intersection state changes.

import React, { useRef } from "react";
import { useIntersectionObserver } from "essential-hooks-collection";

const MyComponent = () => {
const elementRef = useRef<HTMLDivElement>(null);
const isVisible = useIntersectionObserver(elementRef, { threshold: 0.5 });

return (
<div>
<div ref={elementRef}>Observed Element</div>
{isVisible ? <p>The element is visible!</p> : <p>The element is not visible!</p>}
</div>
);
};

export default MyComponent;
  • Type Parameters

    • T extends HTMLElement

      The type of the HTMLElement to observe.

    Parameters

    • ref: RefObject<T>

      A React ref attached to the element that should be observed.

    • Optionaloptions: IntersectionObserverInit = {}

      Optional settings for the IntersectionObserver (e.g., root, rootMargin, threshold).

    Returns boolean

    Returns true if the element is visible (i.e., intersecting), otherwise false.