useIntersectionObserverperformance

useIntersectionObserver

NewSSR SAFE

Triggers when an element enters or leaves the viewport.

$ pnpm dlx shadcn@latest add @byphongphan/use-intersection-observer
Requires @byphongphan in components.json
performance
Loading preview...

Installation

$ pnpm dlx shadcn@latest add @byphongphan/use-intersection-observer
Requires @byphongphan in components.json

Usage

import { useIntersectionObserver } from "@/shared/hooks"
export function LazyCard() { const { ref, isIntersecting } = useIntersectionObserver<HTMLDivElement>({ threshold: 0.5, freezeOnceVisible: true, })
return ( <div ref={ref} className={isIntersecting ? "animate-fade-in" : "opacity-0"} > <h3>Animated Element</h3> <p>Appears once 50% enters viewport.</p> </div> )}

Props & Parameters

ParamTypeDefaultDescription
thresholdnumber | number[]0Either a single number or an array of numbers between 0.0 and 1.0 indicating visibility ratio.
rootElement | Document | nullnullThe element that is used as the viewport for checking visibility. Defaults to browser viewport.
rootMarginstring"0%"Margin around the root element, similar to CSS margin property.
freezeOnceVisiblebooleanfalseWhen true, automatically unobserves element after it first enters viewport.
enabledbooleantrueWhether intersection observer is active.

Returns

ReturnTypeDescription
refRefObject<T | null>React Ref to attach to target DOM element container.
isIntersectingbooleantrue when target is currently intersecting viewport based on threshold.
entryIntersectionObserverEntry | nullRaw native intersection observer entry record.

Command Palette

Quick search and commands navigation