Skip to content

useIntersectionObserver

Element visibility with IntersectionObserver.

A React hook that reports whether an element is in view. Useful for lazy loading, infinite scroll sentinels, and scroll-triggered animations.

Installation

pnpm dlx shadcn@latest add @frontal-labs/use-intersection-observer

Usage

import { useIntersectionObserver } from "@/hooks/use-intersection-observer";
 
function LazySection() {
  const { ref, isIntersecting } = useIntersectionObserver<HTMLDivElement>({
    threshold: 0.5,
  });
 
  return <div ref={ref}>{isIntersecting ? <ExpensiveContent /> : null}</div>;
}

API

function useIntersectionObserver<T extends HTMLElement>(
  options?: IntersectionObserverInit & { enabled?: boolean },
): { ref: RefObject<T | null>; isIntersecting: boolean };

Parameters

Accepts all IntersectionObserverInit options (threshold, root, rootMargin) plus:

Return value