Skip to content

Instantly share code, notes, and snippets.

@timurcatakli
Last active March 9, 2023 23:08
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 timurcatakli/b9a7a718cbb23f7434f09dc3830a12db to your computer and use it in GitHub Desktop.
Save timurcatakli/b9a7a718cbb23f7434f09dc3830a12db to your computer and use it in GitHub Desktop.
import { useEffect, useMemo, useState } from "react";
function useIsInViewPort(ref) {
const [isVisible, setIsVisible] = useState(false);
const observer = useMemo(() => {
return new IntersectionObserver(
([entry]) => {
setIsVisible(entry.isIntersecting);
},
{ threshold: 0.5 },
);
}, [ref]);
useEffect(() => {
observer.observe(ref.current);
return () => {
observer.unobserve(ref.current);
};
}, [ref, observer]);
return isVisible;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment