Created
January 16, 2023 09:09
-
-
Save kp-gists/9b6704425b1512949c7784d4d1a5e34f to your computer and use it in GitHub Desktop.
useOnScreen
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
| import { useEffect, useState } from "react" | |
| export default function useOnScreen(ref, rootMargin = "0px") { | |
| const [isVisible, setIsVisible] = useState(false) | |
| useEffect(() => { | |
| if (ref.current == null) return | |
| const observer = new IntersectionObserver( | |
| ([entry]) => setIsVisible(entry.isIntersecting), | |
| { rootMargin } | |
| ) | |
| observer.observe(ref.current) | |
| return () => { | |
| if (ref.current == null) return | |
| observer.unobserve(ref.current) | |
| } | |
| }, [ref.current, rootMargin]) | |
| return isVisible | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment