# All files / src/_hooks ResizeObserver.ts

100% Statements 16/16
87.5% Branches 7/8
100% Functions 3/3
100% Lines 14/14

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
    24
    25
    26
    27
    288x
    8x

    8x
    1x

    8x

    68x

    68x
    34x
    18x

    16x
    16x

    16x
    3x

    68x

     import React from 'react'
    import ResizeObserverPolyfill from 'resize-observer-polyfill'

    if (!globalThis?.ResizeObserver) {
      globalThis.ResizeObserver = ResizeObserverPolyfill
    }

    export function useResizeObserver<T extends Element = HTMLElement>(
      callback: ResizeObserverCallback
    ): (el: T | null) => void {
      const [el, setEl] = React.useState<T | null>(null)

      React.useEffect(() => {
        if (!el || !callback) {
          return
        }

        const resizeObserver = new window.ResizeObserver(callback)
        resizeObserver.observe(el)

        return () => {
          resizeObserver.disconnect()
        }
      }, [el, callback])

      return setEl
    }