File size: 1,583 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { useState, useRef, useCallback } from 'react'

import { useIsomorphicLayoutEffect } from './useIsomorphicEffect'

export interface DimesionsReadOnly {
  readonly width?: number
  readonly height?: number
}

/**
 *
 * @param function cb(bounds: DimesionsReadOnly) => void
 * called on resize with DimesionsReadOnly object as first argument
 * @returns DimesionsReadOnly
 */
const useWindowSize = (
  cb?: (bounds: DimesionsReadOnly) => void
): DimesionsReadOnly => {
  const [bounds, setBounds] = useState<DimesionsReadOnly>({
    width: undefined,
    height: undefined,
  })

  // hold old dimensions in ref to avoid having to remake the callback below
  const prevDimesions = useRef(bounds)

  const handleResize = useCallback(() => {
    const { innerHeight: height, innerWidth: width } = window
    const newDimensions = {
      height,
      width,
    }
    Object.freeze(newDimensions)
    // if dimensions are not equal, update and re-render
    if (
      !isObjectEqual(prevDimesions.current, newDimensions, ['width', 'height'])
    ) {
      setBounds(newDimensions)

      if (cb) {
        cb(newDimensions)
      }
    }
  }, [cb])

  useIsomorphicLayoutEffect(() => {
    // initial calc
    handleResize()
    window.addEventListener('resize', handleResize)
    return () => {
      window.removeEventListener('resize', handleResize)
    }
  }, [handleResize])

  return bounds
}

const isObjectEqual = <TObject>(
  oldObj: TObject,
  newObj: TObject,
  keys: Array<keyof TObject>
) => keys.every(key => oldObj[key] === newObj[key])

export { useWindowSize }