Skip to main content

useIntersectionObserver

A custom hook that calls the action callback function when the target element assigned ref is exposed to the Viewport.

You can set the Intersection Observer Option (see Note below).


Interface

interface UseIntersectionObserverProps extends IntersectionObserverInit {
action: (entry: IntersectionObserverEntry) => void;
calledOnce?: boolean;
}

const useIntersectionObserver: <T extends HTMLElement>({
action,
calledOnce,
root,
threshold,
rootMargin,
}: UseIntersectionObserverProps) => (node: T) => void;

Usage

import { useIntersectionObserver } from '@devgrace/react';

const Example = () => {
const divRef = useIntersectionObserver<HTMLDivElement>({
action: () => { /* action */},
});
const imgRef = useIntersectionObserver<HTMLImageElement>({
action: (entry) => { /* You can use IntersectionObserverEntry if needed. */},
});

return (
<div>
{/* ... */}
<div ref={divRef}>Box</div>
<img ref={imgRef} src="url" alt="img" />
</div>
);
};

Note

Intersection Observer API