Created
August 4, 2020 09:47
-
-
Save hyber1z0r/08acabc0a396f32ec73bc34563dfe858 to your computer and use it in GitHub Desktop.
useWhenVisible hook
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 React, { useEffect } from 'react'; | |
const useWhenVisible = (target: Element | undefined, | |
callback: () => void, | |
root: Element | undefined = document.body) => { | |
useEffect(() => { | |
if (!target || !root) { | |
return; | |
} | |
const observer = new IntersectionObserver(([entry]) => { | |
if (entry.isIntersecting) { | |
callback(); | |
} | |
}, { root }); | |
observer.observe(target); | |
return () => { | |
observer.unobserve(target); | |
} | |
}, [target, callback, root]); | |
}; | |
export default useWhenVisible; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment