import { useEffect, useMemo, useRef, useState } from "react" interface IUseDynamicSize { defaultWidth?: number defaultHeight?: number } export function useDynamicSize({ defaultWidth = 0, defaultHeight = 0 }: IUseDynamicSize) { const [width, setWidth] = useState(defaultWidth); const [height, setHeight] = useState(defaultHeight); const elementRef = useRef(null); useEffect(() => { if (!elementRef.current) return; const resizeObserver = new ResizeObserver(() => { if (elementRef.current?.clientWidth !== width) { setWidth(elementRef.current?.clientWidth || 0); } if (elementRef.current?.clientHeight !== height) { setHeight(elementRef.current?.clientHeight || 0); } }); resizeObserver.observe(elementRef.current); return function cleanup() { resizeObserver.disconnect(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [elementRef.current]) return useMemo(() => ({ width, height, elementRef }), [width, height, elementRef]) }