AvraamMavridis / react-intersection-visible-hook

React Hook to track the visibility of a functional component
49 stars 4 forks source link

Typescript Version #3

Open artokun opened 5 years ago

artokun commented 5 years ago
import { useRef, useState, useEffect, RefObject } from 'react'
import 'intersection-observer'

type UseVisibilityType = (
  node: RefObject<any>,
  options?: IntersectionObserverInit | undefined
) => IntersectionObserverEntry | object

const useVisibility: UseVisibilityType = (node, options = {}) => {
  const [visible, setVisibilty] = useState({})
  const isIntersecting = useRef({})

  const handleObserverUpdate: IntersectionObserverCallback = entries => {
    const ent = entries[0]

    if (isIntersecting.current !== ent.isIntersecting) {
      setVisibilty(ent)
      isIntersecting.current = ent.isIntersecting
    }
  }

  const observer = new IntersectionObserver(handleObserverUpdate, options)

  useEffect(() => {
    const element = node.current

    if (!element) {
      return
    }

    observer.observe(element)

    return function cleanup() {
      observer.unobserve(element)
    }
  })

  return visible
}

export { useVisibility }
artokun commented 5 years ago

Once I am done with my current branch I'll share my tests

AvraamMavridis commented 5 years ago

@artokun feel free to open a PR if you feel like.