Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Last active September 3, 2019 20:22
Show Gist options
  • Select an option

  • Save itsMapleLeaf/362810b3de6c36320de6fa364da8cef1 to your computer and use it in GitHub Desktop.

Select an option

Save itsMapleLeaf/362810b3de6c36320de6fa364da8cef1 to your computer and use it in GitHub Desktop.
useWindowIntersection
function Example() {
const elementRef = useRef<HTMLDivElement>(null) // ref for the element you want to watch
const isInsideWindow = useWindowIntersection(elementRef)
return <div ref={elementRef}>
is inside window: {isInWindow}
</div>
}
import { useState, useEffect } from "react"
export default function useWindowIntersection<E extends Element>(
targetRef: React.RefObject<E>,
) {
const [isInWindow, setIsInWindow] = useState(false)
useEffect(() => {
if (!targetRef.current) return
const observer = new IntersectionObserver((entries) => {
setIsInWindow(entries.some((entry) => entry.isIntersecting))
})
observer.observe(targetRef.current)
return () => observer.disconnect()
}, [targetRef])
return isInWindow
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment