Docs
useIntersectionObserver

A hook that provides a way to detect when an element enters or leaves the viewport using the Intersection Observer API.

Installation

pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-intersection-observer

Usage

"use client"
 
import * as React from "react"
 
import { useIntersectionObserver } from "@/hooks/use-intersection-observer"
 
export function Component() {
  const targetRef = React.useRef<HTMLDivElement>(null)
 
  const entry = useIntersectionObserver(targetRef, {
    threshold: 0.5, // Trigger when 50% of the element is visible
    rootMargin: "0px", // No margin around the root
  })
 
  const isVisible = entry?.isIntersecting ?? false
 
  return (
    <div
      ref={targetRef}
      style={{
        width: "100px",
        height: "100px",
        backgroundColor: isVisible ? "green" : "red",
      }}
    >
      {isVisible ? "Visible" : "Not Visible"}
    </div>
  )
}

API Reference

Parameters

NameTypeDescriptionDefault ValueOptional
elementRefReact.RefObject<T>A React ref object pointing to the target element to observe.-No
optionsUseIntersectionObserverPropsOptional configuration for the Intersection Observer.See BelowYes

Props

NameTypeDefaultDescription
threshold?number | number[]0(Optional) The percentage of the target's visibility required to trigger the observer.
root?Element | Document | nullnull(Optional) The root element used as the viewport for checking visibility.
rootMargin?string"0%"(Optional) Margin around the root element to grow or shrink the intersection area.

Return Values

NameTypeDescription
entryIntersectionObserverEntry | undefinedThe intersection observer entry containing details about the target element.

IntersectionObserverEntry Key Properties

NameTypeDescription
isIntersectingbooleanIndicates whether the target element is intersecting with the root.
intersectionRationumberThe ratio of the target element's visibility (between 0 and 1).
boundingClientRectDOMRectReadOnlyThe bounding rectangle of the target element.
rootBoundsDOMRectReadOnly | nullThe bounding rectangle of the root element.
timenumberThe timestamp when the intersection was recorded.

Notes

  • Ensure the IntersectionObserver API is supported in your target browsers. If not, consider using a polyfill.
  • The hook automatically cleans up the observer when the component unmounts or the elementRef changes.