import debounce from 'lodash/debounce';
import { useLayoutEffect, useState } from 'react';

export const useWindowSize = (): {
  height: number;
  width: number;
} => {
  const [size, setSize] = useState({ height: 0, width: 0 });

  useLayoutEffect(() => {
    // debounce is needed to avoid re-rendering everything on every resize event
    const updateSize = debounce(() => {
      setSize({ height: window.innerHeight, width: window.innerWidth });
    }, 50);

    // add window resize event listener on mount
    window.addEventListener('resize', updateSize);

    updateSize();

    // remove window resize event listener on unmount
    return () => {
      updateSize.cancel();
      window.removeEventListener('resize', updateSize);
    };
  }, []);

  return size;
};

// This hook is based off: https://stackoverflow.com/a/19014495
