Skip to content

Instantly share code, notes, and snippets.

@hyber1z0r
Created August 4, 2020 09:47
Show Gist options
  • Save hyber1z0r/08acabc0a396f32ec73bc34563dfe858 to your computer and use it in GitHub Desktop.
Save hyber1z0r/08acabc0a396f32ec73bc34563dfe858 to your computer and use it in GitHub Desktop.
useWhenVisible hook
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