2022-05-17 23:29:46 +00:00
|
|
|
import { useEffect, useState } from 'react'
|
2022-03-17 07:29:08 +00:00
|
|
|
|
2022-05-17 23:29:46 +00:00
|
|
|
export function useIsVisible(element: HTMLElement | null) {
|
|
|
|
return !!useIntersectionObserver(element)?.isIntersecting
|
2022-03-17 07:29:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function useIntersectionObserver(
|
2022-05-17 23:29:46 +00:00
|
|
|
elem: HTMLElement | null
|
2022-03-17 07:29:08 +00:00
|
|
|
): IntersectionObserverEntry | undefined {
|
|
|
|
const [entry, setEntry] = useState<IntersectionObserverEntry>()
|
|
|
|
|
|
|
|
const updateEntry = ([entry]: IntersectionObserverEntry[]): void => {
|
|
|
|
setEntry(entry)
|
|
|
|
}
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
const hasIOSupport = !!window.IntersectionObserver
|
|
|
|
|
2022-05-17 23:29:46 +00:00
|
|
|
if (!hasIOSupport || !elem) return
|
2022-03-17 07:29:08 +00:00
|
|
|
|
|
|
|
const observer = new IntersectionObserver(updateEntry, {})
|
2022-05-17 23:29:46 +00:00
|
|
|
observer.observe(elem)
|
2022-03-17 07:29:08 +00:00
|
|
|
|
|
|
|
return () => observer.disconnect()
|
2022-05-17 23:29:46 +00:00
|
|
|
}, [elem])
|
2022-03-17 07:29:08 +00:00
|
|
|
|
|
|
|
return entry
|
|
|
|
}
|