1
0
mirror of synced 2025-12-19 18:10:59 -05:00
Files
docs/components/hooks/useOnScreen.ts
Mike Surowiec 06d8f81401 Two-pane Experiment (#21092)
* pull changes from docs-playground

* cleanup, add callout banner

* cleanup linting and test fixes

* add discussion link

Co-authored-by: James M. Greene <JamesMGreene@github.com>
2021-08-26 14:19:40 -04:00

25 lines
708 B
TypeScript

import { useState, useEffect, MutableRefObject, RefObject } from 'react'
export function useOnScreen<T extends Element>(
ref: MutableRefObject<T | undefined> | RefObject<T>,
options?: IntersectionObserverInit
): boolean {
const [isIntersecting, setIntersecting] = useState(false)
useEffect(() => {
let isMounted = true
const observer = new IntersectionObserver(([entry]) => {
isMounted && setIntersecting(entry.isIntersecting)
}, options)
if (ref.current) {
observer.observe(ref.current)
}
return () => {
isMounted = false
ref.current && observer.unobserve(ref.current)
}
}, [Object.values(options || {}).join(',')])
return isIntersecting
}