Skip to main content

Function: useIntersectionObserver()

@arolariu/components


@arolariu/components / useIntersectionObserver

Function: useIntersectionObserver()

useIntersectionObserver(ref, options?): IntersectionObserverEntry

Defined in: hooks/useIntersectionObserver.tsx:53

Observes element visibility using the Intersection Observer API.

Parameters

ref

RefObject<Element>

A React ref object pointing to the element to observe.

options?

IntersectionObserverInit

Optional IntersectionObserver configuration (threshold, root, rootMargin).

Returns

IntersectionObserverEntry

The latest IntersectionObserverEntry or null if not intersecting yet.

Remarks

This hook creates an IntersectionObserver that watches the provided element reference and returns the latest IntersectionObserverEntry. It's useful for implementing lazy loading, infinite scroll, animations on scroll, and tracking element visibility.

The observer automatically disconnects when the component unmounts or when the element reference changes. The hook is SSR-safe and returns null when running on the server or when the observer is not yet initialized.

Examples

function LazyImage({src, alt}: {src: string; alt: string}) {
const imageRef = useRef<HTMLImageElement>(null);
const entry = useIntersectionObserver(imageRef, {threshold: 0.1});

return (
<img
ref={imageRef}
src={entry?.isIntersecting ? src : undefined}
alt={alt}
/>
);
}
function AnimateOnScroll({children}: {children: React.ReactNode}) {
const ref = useRef<HTMLDivElement>(null);
const entry = useIntersectionObserver(ref, {threshold: 0.5});
const isVisible = entry?.isIntersecting ?? false;

return (
<div ref={ref} className={isVisible ? "fade-in" : "hidden"}>
{children}
</div>
);
}
// was this page useful?