useIntersectionObserver

Layout/Viewport

A React hook that tracks when an element enters or leaves the viewport using the Intersection Observer API for efficient visibility detection.

Installation

npm install @thibault.sh/hooks

API Reference

Signature


interface IntersectionOptions extends IntersectionObserverInit {
  freezeOnceVisible?: boolean;
}

function useIntersectionObserver(
  elementRef: RefObject<HTMLElement>,
  options?: IntersectionOptions
): IntersectionObserverEntry | null

Parameters

NameTypeDescriptionDefault
elementRef
RefObject<HTMLElement>
React ref object pointing to the target element to observe.-
options
optional
IntersectionOptions
Configuration options for the intersection observer.-
options.threshold
optional
number | number[]
Percentage of visibility at which callback should trigger (0-1).0
options.root
optional
Element | null
Element used as viewport for checking visibility.null
options.rootMargin
optional
string
Margin around the root element (CSS-like syntax).0%
options.freezeOnceVisible
optional
boolean
If true, stops observing once element becomes visible.false

Returns

IntersectionObserverEntry | null

IntersectionObserverEntry object containing visibility information, or null if element not found.

Properties:

PropertyTypeDescription
isIntersecting
boolean
Whether the element is currently intersecting with the viewport.
intersectionRatio
number
Ratio of intersection area to total bounding box area (0-1).
boundingClientRect
DOMRectReadOnly
Bounding rectangle of the target element.