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.jsonOptions
| Option | Type | Default | Description |
|---|---|---|---|
| threshold | number | number[] | 0 | A number or array of numbers indicating at what percentage of the target's visibility the observer's callback should be executed. |
| root | Element | null | null | The element that is used as the viewport for checking visibility of the target. Must be the ancestor of the target. |
| rootMargin | string | "0px" | Margin around the root. Can have values similar to the CSS margin property. |
| freezeOnceVisible | boolean | false | Whether to freeze the observer once the element is visible. Useful for animations that should only trigger once. |
| initialIsIntersecting | boolean | false | Initial state of the intersection before the observer is set up. |
Return Values
| Property | Type | Description |
|---|---|---|
| ref | (node: Element | null) => void | Callback ref to attach to the element you want to observe |
| entry | IntersectionObserverEntry | undefined | Full IntersectionObserverEntry object with intersection details |
| isIntersecting | boolean | Whether the element is currently intersecting with the viewport |