Skip to content

useIntersectionObserver

useIntersectionObserver is a React hook that detects whether a specific DOM element is visible on the screen. It uses the IntersectionObserver API to execute a callback when the element enters or exits the viewport.

Interface

ts
function useIntersectionObserver(
  callback: (entry: IntersectionObserverEntry) => void,
  options: IntersectionObserverInit
): (element: Element | null) => void;

Parameters

  • callbackrequired · (entry: IntersectionObserverEntry) => void

    A callback function that is executed when the visibility of the element changes. You can check entry.isIntersecting to determine if the element is in view.

  • optionsrequired · IntersectionObserverInit

    Options for the IntersectionObserver. You can specify values such as root, rootMargin, and threshold.

Return Value

  • (element: Element | null) => void

    function to set the element. Attach this function to the ref attribute, and the callback will be executed whenever the element's visibility changes.

Example

tsx
import { useIntersectionObserver } from 'react-simplikit';

function Component() {
  const ref = useIntersectionObserver<HTMLDivElement>(
    entry => {
      if (entry.isIntersecting) {
        console.log('Element is in view:', entry.target);
      } else {
        console.log('Element is out of view:', entry.target);
      }
    },
    { threshold: 0.5 }
  );

  return <div ref={ref}>Observe me!</div>;
}

Released under the MIT License.