Skip to content

Instantly share code, notes, and snippets.

@reyronald
Created October 4, 2022 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reyronald/90187460ea920604004cc20169c4fa36 to your computer and use it in GitHub Desktop.
Save reyronald/90187460ea920604004cc20169c4fa36 to your computer and use it in GitHub Desktop.
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