Skip to content

Instantly share code, notes, and snippets.

@kp-gists
Created January 16, 2023 09:09
Show Gist options
  • Save kp-gists/9b6704425b1512949c7784d4d1a5e34f to your computer and use it in GitHub Desktop.
Save kp-gists/9b6704425b1512949c7784d4d1a5e34f to your computer and use it in GitHub Desktop.
useOnScreen
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