Created
October 22, 2019 14:19
-
-
Save solilokiam/ad6033409e0d010872c6163527d1ba46 to your computer and use it in GitHub Desktop.
OnScreenHook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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