1
0
mirror of synced 2025-12-22 11:26:57 -05:00
Files
docs/components/hooks/useOnScreen.tsx
Mike Surowiec a88e99c83a Reactify: release notes (#19799)
* reactify release-notes pages

* update GHAE/ES react release notes to not rely on javascripts/release-notes.js
2021-06-09 20:44:32 +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
}