import { useEffect, useMemo, useState } from 'react'

import { useIsMounted } from './useIsMounted'

/**
 * A utility hook that lets you read the dimensions of the screen and automatically
 * updates on resize.
 */
export function useScreenSize() {
  const isMounted = useIsMounted()
  const [width, setWidth] = useState(0)
  const [height, setHeight] = useState(0)

  useEffect(() => {
    if (!isMounted) {
      return
    }

    const handler = () => {
      setWidth(window.innerWidth)
      setHeight(window.innerHeight)
    }

    // Trigger immediately.
    handler()

    // Subscribe to resize event.
    window.addEventListener('resize', handler)
    return () => window.removeEventListener('resize', handler)
  }, [setWidth, setHeight, isMounted])

  const size = useMemo(() => {
    return { width, height }
  }, [width, height])

  return size
}
