import { useEffect } from 'react';
import ResizeObserver from 'resize-observer-polyfill';

/**
 * React implementation of the Resize Observer Interface to tell you when an element resizes.
 * Pass a callback function and an Element to handle ResizeObserver callbacks.
 *
 * @param callback
 * @param target
 */
const useResizeObserverEffect = (callback: () => void, target: HTMLElement | null) => {
  useEffect(() => {
    callback();
    const observer = new ResizeObserver(callback);
    target && observer?.observe(target);
    return () => observer?.disconnect();
  }, [callback, target]);
};

export default useResizeObserverEffect;
