Last active
March 21, 2024 11:37
-
-
Save Keireira/e237ef74ed0f9faa33f21e7293f074b8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| const useOnScreen = (ref: ObjectRef, rootMargin: number = 0) => { | |
| const ioSupported = 'IntersectionObserver' in window | |
| const [visible, setVisible] = useState(false) | |
| /* fallback for browsers with no IntersectionObserver support */ | |
| useOnScreenFallback({ ref, ioSupported, setVisible }) | |
| useEffect(() => { | |
| if (!ioSupported) { | |
| return | |
| } | |
| const observer = new window.IntersectionObserver( | |
| ([entry]) => setVisible(entry.isIntersecting), | |
| { rootMargin: `${rootMargin * getRem()}px` } | |
| ) | |
| if (ref.current) { | |
| observer.observe(ref.current) | |
| } | |
| return () => { | |
| observer.unobserve(ref.current) | |
| } | |
| }, []) | |
| return visible | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment