Skip to content

Instantly share code, notes, and snippets.

@Tim-W-James
Created February 12, 2023 06:37
Show Gist options
  • Select an option

  • Save Tim-W-James/a750c8a3b53e6bbe0ba22ac1cfe314a4 to your computer and use it in GitHub Desktop.

Select an option

Save Tim-W-James/a750c8a3b53e6bbe0ba22ac1cfe314a4 to your computer and use it in GitHub Desktop.
React useIntersectionObserver Custom Hook #hooks
import { RefObject, useEffect, useState } from "react";
const useIntersectionObserver = (
ref: RefObject<Element>,
rootMargin = "0px"
): boolean => {
const [isVisible, setIsVisible] = useState(false);
useEffect(() => {
const current = ref.current;
if (current == null) {
return;
}
const observer = new IntersectionObserver(
([entry]) => setIsVisible(entry?.isIntersecting || false),
{ rootMargin }
);
observer.observe(current);
return () => {
observer.unobserve(current);
};
}, [ref, rootMargin]);
return isVisible;
};
export default useIntersectionObserver;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment