useIntersection

A custom React hook for using the Intersection Observer API with TypeScript support and freezeOnceVisible option.

Intersection Observer Hook Demo

Scroll down to see the intersection observer in action

Example 1: Basic (80% threshold)

Status: ❌ Hidden

This box changes color when 80% of it is visible in the viewport.

Example 2: Freeze Once Visible

Status: ❌ Hidden

Once this box becomes visible, it stays highlighted even when you scroll past it. (100% threshold)

Example 3: Custom Root Margin

Status: ❌ Hidden

This box triggers 160px before it enters the viewport using negative root margin.

Installation

pnpx shadcn@latest add https://jharsh.me/r/use-intersection-observer.json

Options

OptionTypeDefaultDescription
thresholdnumber | number[]0A number or array of numbers indicating at what percentage of the target's visibility the observer's callback should be executed.
rootElement | nullnullThe element that is used as the viewport for checking visibility of the target. Must be the ancestor of the target.
rootMarginstring"0px"Margin around the root. Can have values similar to the CSS margin property.
freezeOnceVisiblebooleanfalseWhether to freeze the observer once the element is visible. Useful for animations that should only trigger once.
initialIsIntersectingbooleanfalseInitial state of the intersection before the observer is set up.

Return Values

PropertyTypeDescription
ref(node: Element | null) => voidCallback ref to attach to the element you want to observe
entryIntersectionObserverEntry | undefinedFull IntersectionObserverEntry object with intersection details
isIntersectingbooleanWhether the element is currently intersecting with the viewport