Skip to content

Instantly share code, notes, and snippets.

@bagus2x
Created August 5, 2021 18:10
Show Gist options
  • Save bagus2x/7bd68e8b83b088be28937746b8461c60 to your computer and use it in GitHub Desktop.
Save bagus2x/7bd68e8b83b088be28937746b8461c60 to your computer and use it in GitHub Desktop.
simple Intersection Observer hook
import { MutableRefObject, useEffect, useRef } from 'react';
interface Options<Target> {
root?: MutableRefObject<any>;
enabled?: boolean;
rootMargin?: string;
threshold: number;
onIntersect: (entry?: IntersectionObserverEntry, target?: Target) => void;
}
const useIntersectionObserver = <Target extends Element>({
root,
enabled = true,
rootMargin,
threshold = 1,
onIntersect
}: Options<Target>) => {
const targetRef = useRef<Target>(null);
useEffect(() => {
if (!enabled) return;
const observer = new IntersectionObserver(
(entries) => {
return entries.forEach((entry) => {
if (targetRef.current) onIntersect(entry, targetRef.current);
});
},
{
root: root && root.current,
rootMargin,
threshold
}
);
if (!targetRef || !targetRef.current) return;
const el = targetRef.current;
observer.observe(el);
return () => {
if (el) observer.unobserve(el);
};
}, [enabled, root, rootMargin, threshold, onIntersect]);
return targetRef;
};
export default useIntersectionObserver;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment