import {MutableRefObject, RefObject, useLayoutEffect, useState} from 'react';
import useResizeObserver from '@react-hook/resize-observer';

export function useSize(target: MutableRefObject<HTMLElement> | RefObject<HTMLElement>) {
    const [size, setSize] = useState<DOMRect | null>(null);

    useLayoutEffect(() => {
        if (target.current) {
            setSize(target.current.getBoundingClientRect());
        }
    }, [target]);

    useResizeObserver(target, (entry) => setSize(entry.contentRect));
    return size;
}
