import { useEffect } from 'react';

import { useEffectEvent } from './useEffectEvent';

export function useResizeObserver(
  ref: React.MutableRefObject<Element | null>,
  callback: (entry: ResizeObserverEntry) => void,
  box: ResizeObserverBoxOptions = 'border-box',
) {
  const handleCallback = useEffectEvent(callback);
  useEffect(() => {
    if (ref.current != null) {
      const resizeObserver = new ResizeObserver(([entry]) => {
        handleCallback(entry);
      });
      resizeObserver.observe(ref.current, { box });
      return () => {
        resizeObserver.disconnect();
      };
    }
    return () => {};
  }, [handleCallback, ref, box]);
}
