# All files / src/_hooks/IntersectionObserver useIntersectionObserver.ts

100% Statements 15/15
75% Branches 3/4
100% Functions 3/3
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    246x

    6x

    6x

    67x

    67x

    67x
    45x
    17x

    28x
    28x
    28x
    20x

    67x

     import React from 'react'

    import { createIntersectionObserver } from './createIntersectionObserver'

    export function useIntersectionObserver<T extends Element = HTMLElement>(
      callback: IntersectionObserverCallback,
      Ioptions: IntersectionObserverInit = {}
    ): (el: T | null | undefined) => void {
      const [el, setEl] = React.useState<T | null | undefined>(null)

      React.useEffect(() => {
        if (!el || !callback) {
          return
        }
        const observer = createIntersectionObserver(callback, options)
        observer.observe(el)
        return () => {
          observer.disconnect()
        }
      }, [el, callback, options])

      return setEl
    }