useIntersectionObserver

A hook that monitors the visibility and intersection of a DOM element within a viewport.

Note

If you are using this for "Lazy Loading" images or infinite scroll, the once: true option is highly recommended to improve performance by disconnecting the observer after the first successful intersection.

Tip

You can pass an externalRef as a second argument if you need to share the reference with other hooks or components.

Installation

bash

Description

The useIntersectionObserver provides a declarative wrapper around the native Intersection Observer API. It is ideal for implementing lazy loading, infinite scrolling, or scroll-triggered animations. It supports a "once" mode that disconnects the observer after the first successful intersection and can accept an external ref or manage its own internal one.

Parameters

NameTypeDescription
options.rootElement | DocumentThe element that is used as the viewport for checking visibility.
options.rootMarginstringMargin around the root (e.g., '10px 20px 30px 40px'). Default: '0px'.
options.thresholdnumber | number[]Percentage of the target's visibility at which the observer's callback should execute. Default: 0.
options.oncebooleanIf true, the observer disconnects after the first time the element becomes visible. Default: 'false'.
options.onChange(entry) => voidCallback triggered whenever an intersection change occurs.
externalRefReact.RefObject<T>Optional external ref to use instead of the internally created ref.

Return values

NameTypeDescription
entryIntersectionObserverEntry | nullThe latest intersection entry object containing detailed position and ratio data.
isVisiblebooleanReactive state indicating if the element is currently intersecting with the root.
refReact.RefObject<T>The ref to be assigned to the element you wish to observe.

Demo

Intersection Observer

Visible on scroll 👀

Source code

tsx