bigbuffet-rw/packages/pl-fe/src/hooks/useDimensions.ts
marcin mikołajczak 4d5690d0c1 Switch to workspace
Signed-off-by: marcin mikołajczak <git@mkljczk.pl>
2024-08-28 13:01:08 +02:00

38 lines
878 B
TypeScript

import { useEffect, useMemo, useState } from 'react';
type UseDimensionsRect = { width: number; height: number };
type UseDimensionsResult = [Element | null, any, any]
const defaultState: UseDimensionsRect = {
width: 0,
height: 0,
};
const useDimensions = (): UseDimensionsResult => {
const [element, setRef] = useState<Element | null>(null);
const [rect, setRect] = useState<UseDimensionsRect>(defaultState);
const observer = useMemo(
() =>
new ResizeObserver((entries: any) => {
if (entries[0]) {
const { width, height } = entries[0].contentRect;
setRect({ width, height });
}
}),
[],
);
useEffect(() => {
if (!element) return;
observer.observe(element);
return () => {
observer.disconnect();
};
}, [element]);
return [element, setRef, rect];
};
export { useDimensions };