Skip to content

Instantly share code, notes, and snippets.

@Keireira
Last active March 21, 2024 11:37
Show Gist options
  • Select an option

  • Save Keireira/e237ef74ed0f9faa33f21e7293f074b8 to your computer and use it in GitHub Desktop.

Select an option

Save Keireira/e237ef74ed0f9faa33f21e7293f074b8 to your computer and use it in GitHub Desktop.
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