Skip to content

Instantly share code, notes, and snippets.

@solilokiam
Created October 22, 2019 14:19
Show Gist options
  • Save solilokiam/ad6033409e0d010872c6163527d1ba46 to your computer and use it in GitHub Desktop.
Save solilokiam/ad6033409e0d010872c6163527d1ba46 to your computer and use it in GitHub Desktop.
OnScreenHook
import { useState, useEffect } from 'react';
const useOnScreen = (ref, rootMargin = '0px') => {
const [isIntersecting, setIntersecting] = useState(false);
useEffect(() => {
if (IntersectionObserver) {
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
setIntersecting(true);
}
},
{
rootMargin,
}
);
if (ref.current) {
observer.observe(ref.current);
}
return () => {
observer.unobserve(ref.current);
};
}
setIntersecting(true);
return null;
}, []);
return isIntersecting;
};
export default useOnScreen;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment