Created
April 9, 2023 12:20
-
-
Save tjinlag/9a80bec48eafd0000c1f245931893d30 to your computer and use it in GitHub Desktop.
React Custom Hook: useOnScreen
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
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