Skip to content

Instantly share code, notes, and snippets.

@hamidjafari
Created May 29, 2021 20:52
Show Gist options
  • Save hamidjafari/155d587e2da341871e4091c3c8433648 to your computer and use it in GitHub Desktop.
Save hamidjafari/155d587e2da341871e4091c3c8433648 to your computer and use it in GitHub Desktop.
custom hook for track elements visibility on screen in react component using ref
function useOnScreen(
ref: React.RefObject<HTMLElement>,
disconnectAfterIntersect: boolean
) {
const [isIntersecting, setIntersecting] = useState(false);
const observer = useMemo(() => {
return new IntersectionObserver(([entry]) => {
setIntersecting(entry.isIntersecting);
});
}, []);
useEffect(() => {
if (!ref.current) return;
observer.observe(ref.current);
return () => {
observer.disconnect();
};
}, []);
useEffect(() => {
if (isIntersecting && disconnectAfterIntersect) {
observer.disconnect();
}
}, [isIntersecting]);
return isIntersecting;
}
@hamidjafari
Copy link
Author

you can use this custom hook to track nodes visibility on screen using ref

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment