1
0
mirror of synced 2025-12-21 10:57:10 -05:00
Files
docs/components/hooks/useOnScreen.ts
Mike Surowiec 85b48a3795 Rename hooks/lib files to .ts (#20488)
* rename hooks to .ts

* rename lib files to ts
2021-07-26 14:37:21 +00:00

26 lines
642 B
TypeScript

import { useState, useEffect, MutableRefObject, RefObject } from 'react'
export function useOnScreen<T extends Element>(
ref: MutableRefObject<T | undefined> | RefObject<T>,
rootMargin: string = '0px'
): boolean {
const [isIntersecting, setIntersecting] = useState(false)
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => {
setIntersecting(entry.isIntersecting)
},
{
rootMargin,
}
)
if (ref.current) {
observer.observe(ref.current)
}
return () => {
ref.current && observer.unobserve(ref.current)
}
}, [])
return isIntersecting
}