jackmerrill.com/util/hooks/useOnScreen.ts

20 lines
486 B
TypeScript
Raw Normal View History

2021-09-03 10:13:30 -07:00
import { useState, useEffect } from 'react';
2021-10-04 15:13:53 -07:00
export default function useOnScreen(ref: any) {
2021-09-03 10:13:30 -07:00
2021-10-04 15:13:53 -07:00
let observer: any = null
2021-09-03 10:13:30 -07:00
const [isIntersecting, setIntersecting] = useState(false)
useEffect(() => {
observer = new IntersectionObserver(
([entry]) => setIntersecting(entry.isIntersecting)
)
observer.observe(ref.current)
// Remove the observer as soon as the component is unmounted
return () => { observer.disconnect() }
}, [])
return isIntersecting
}