jackmerrill.com/util/hooks/useOnScreen.ts
2021-09-03 17:13:30 +00:00

20 lines
476 B
TypeScript

import { useState, useEffect } from 'react';
export default function useOnScreen(ref) {
let observer = null
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
}