w-aura/src/hooks/useDynamicSize.ts
Daniil Chemerkin e8bec3ceef redesignAB
2024-05-14 20:18:56 +00:00

38 lines
1.2 KiB
TypeScript

import { useEffect, useMemo, useRef, useState } from "react"
interface IUseDynamicSize {
defaultWidth?: number
defaultHeight?: number
}
export function useDynamicSize<T extends HTMLElement>({ defaultWidth = 0, defaultHeight = 0 }: IUseDynamicSize) {
const [width, setWidth] = useState<number>(defaultWidth);
const [height, setHeight] = useState<number>(defaultHeight);
const elementRef = useRef<T>(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])
}