Last active
May 17, 2020 15:01
-
-
Save Rohitbels/66e412cba9d9aa06f342039217fb4bdd to your computer and use it in GitHub Desktop.
Intersection Observer 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 { useEffect } from 'react'; | |
// This customEffect will invoke the callback immediately when the element mention in ref is with viewport i.e. root | |
// intersectionRatio >= 0.1 implies execute callback as soon as element is in view port | |
const useVisibility = (ref, callback, options = {}) => { | |
const { root = null, rootMargin = '0px' } = options; | |
useEffect(() => { | |
if (window.IntersectionObserver) { | |
const observer = new IntersectionObserver(([entry]) => { | |
if (entry.intersectionRatio >= 0.1) { | |
callback(); | |
observer.unobserve(entry.target); | |
observer.disconnect(); | |
} | |
}, { | |
root, | |
rootMargin, | |
threshold: [0.1] | |
}); | |
if (ref.current) { | |
observer.observe(ref.current); | |
} | |
} else { | |
callback(); | |
} | |
}, []); | |
}; | |
export default useVisibility; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment