HooksuseIntersectionObserver

useIntersectionObserver()

The useIntersectionObserver() hook provides a declarative way to track the visibility of a DOM element within the viewport. Itβ€˜s ideal for lazy loading, infinite scrolls, or triggering animations.

Import

typescript
import { useIntersectionObserver } from 'the-react-hooks';

Usage

Scroll inside the box below ↓

Scroll down...

Keep scrolling...

Hidden πŸ™ˆ

End of content

Is IntersectingNO
Intersection Ratio0.00
Component.tsx
import { useIntersectionObserver } from 'the-react-hooks';

export const Component = () => {
  const [ref, entry] = useIntersectionObserver({
    threshold: 0.5,
  });

  return (
    <div>
      <div>Scroll down...</div>
      
      <div ref={ref}>
        {entry?.isIntersecting ? 'Visible' : 'Hidden'}
      </div>
      
      <div>Keep scrolling...</div>
    </div>
  );
}

API

Arguments

Accepts an optional object with the following properties:
  • threshold – number | number[] (Optional) A number between 0 and 1 indicating the percentage of the target that should be visible before triggering. Defaults to 0.
  • root – Element | Document | null (Optional) The element used as the viewport. Defaults to the browser viewport.
  • rootMargin – string (Optional) Margin around the root. Defaults to β€˜0%β€˜.
  • freezeOnceVisible – boolean (Optional) If true, the observer will disconnect after the element becomes visible once. Defaults to false.

Returns

Returns a tuple (array) containing:
  • [0] ref – (node: Element | null) => void A callback ref to attach to the target element.
  • [1] entry – IntersectionObserverEntry | null The full IntersectionObserverEntry object.