Created
October 4, 2022 14:41
-
-
Save reyronald/90187460ea920604004cc20169c4fa36 to your computer and use it in GitHub Desktop.
This file contains 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 { useRef, useState, useEffect } from "react"; | |
export function useIntersectionObserver<THTMLElement extends HTMLElement>( | |
options?: IntersectionObserverInit, | |
) { | |
const ref = useRef<THTMLElement>(null); | |
const [entry, setEntry] = useState<IntersectionObserverEntry | undefined>(); | |
const optionsRef = useRef(options); | |
useEffect(() => { | |
optionsRef.current = options; | |
}, [options]); | |
useEffect(() => { | |
const target = ref.current; | |
if (!target) { | |
return; | |
} | |
const observer = new IntersectionObserver( | |
(entries) => { | |
const entry = entries.find((e) => e.target === target); | |
setEntry(entry); | |
}, | |
{ | |
root: null, | |
rootMargin: "0px", | |
threshold: 0, | |
...optionsRef.current, | |
}, | |
); | |
observer.observe(target); | |
return () => { | |
observer.disconnect(); | |
}; | |
}, []); | |
return { ref, entry }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment