Skip to content

Instantly share code, notes, and snippets.

@hi-ogawa
Created September 14, 2022 05:32
Show Gist options
  • Save hi-ogawa/b273d5f0a8dd39758e796dc6f885ee35 to your computer and use it in GitHub Desktop.
Save hi-ogawa/b273d5f0a8dd39758e796dc6f885ee35 to your computer and use it in GitHub Desktop.
useIntersectionObserverEntry
// const ref = useIntersectionObserverEntry(entry => console.log(entry))
// return <div ref={ref}>...</div>
function useIntersectionObserverEntry(
callback: (value?: IntersectionObserverEntry) => void
): React.RefCallback<Element> {
const observerRef = React.useRef<IntersectionObserver>();
const callbackRef = React.useRef<typeof callback>(callback);
callbackRef.current = callback;
return React.useCallback(el => {
if (el) {
const observer = new IntersectionObserver(entries => {
callbackRef.current(entries[0]);
});
observer.observe(el);
observerRef.current = observer;
} else {
callbackRef.current(undefined);
observerRef.current?.disconnect();
}
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment