Created
August 5, 2021 18:10
-
-
Save bagus2x/7bd68e8b83b088be28937746b8461c60 to your computer and use it in GitHub Desktop.
simple Intersection Observer hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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