Created
May 29, 2021 20:52
-
-
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
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
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you can use this custom hook to track nodes visibility on screen using ref