Skip to content

useIntersectionObserver

useIntersectionObserver is a powerful hook that allows you to observe the intersection of a target element with the viewport or another element. It provides a way to detect when an element is visible in the viewport or when it enters or leaves the viewport.

Anatomy

declare function useIntersectionObserver<T extends HTMLElement>(
options?: IntersectionObserverInit
): readonly [
react.MutableRefObject<T>,
IntersectionObserverEntry | null,
IntersectionObserver,
];

Usage

import { useIntersectionObserver } from "@frend-digital/ui/hooks";
const Component = () => {
const [ref, entry] = useIntersectionObserver();
const isVisible = entry?.isIntersecting;
return <div ref={ref}>{isVisible && <p>Element is visible</p>}</div>;
};

useIntersectionObserverAPI

Need more control over the intersection observer? useIntersectionObserverAPI is a more advanced hook that allows you to customize the intersection observer configuration.

Usage

import { useIntersectionObserverAPI } from "@frend-digital/ui/hooks";
const Component = () => {
const observer = useIntersectionObserverAPI((entries) => {
console.log(entries); // Logs whenever one of the entries observed is intersecting
});
return (
<div>
{Array.from({ length: 3 })
.fill(0)
.map((_, index) => (
<div
key={index}
ref={(el) => {
if (el) {
observer.observe(el);
return () => observer.unobserve(el);
}
}}
>
{index}
</div>
))}
</div>
);
};