diff --git a/src/hooks/useIntersectionObserver.ts b/src/hooks/useIntersectionObserver.ts new file mode 100644 index 00000000..6bc08005 --- /dev/null +++ b/src/hooks/useIntersectionObserver.ts @@ -0,0 +1,29 @@ +import { useEffect, useRef, useState } from 'react'; + +export const useIntersectionObserver = ({ + threshold = 0, + root = null, + rootMargin = '0%', +}: IntersectionObserverInit) => { + const ref = useRef(null); + const [entry, setEntry] = useState(); + + useEffect(() => { + if (!ref.current) { + return; + } + + const observer = new IntersectionObserver( + ([entry]) => { + setEntry(entry); + }, + { threshold, root, rootMargin } + ); + + observer.observe(ref.current); + + return () => observer.disconnect(); + }, [ref, threshold, root, rootMargin]); + + return [ref, entry] as const; +};