Skip to content

Instantly share code, notes, and snippets.

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