Skip to content

Instantly share code, notes, and snippets.

@Rohitbels
Last active May 17, 2020 15:01
Show Gist options
  • Save Rohitbels/66e412cba9d9aa06f342039217fb4bdd to your computer and use it in GitHub Desktop.
Save Rohitbels/66e412cba9d9aa06f342039217fb4bdd to your computer and use it in GitHub Desktop.
Intersection Observer Hook
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