2022-07-18 10:36:56 -07:00
|
|
|
import { useEffect, useMemo, useState } from 'react';
|
2022-06-22 06:25:46 -07:00
|
|
|
|
|
|
|
type UseDimensionsRect = { width: number, height: number };
|
2022-07-18 10:36:56 -07:00
|
|
|
type UseDimensionsResult = [Element | null, any, any]
|
2022-06-22 06:25:46 -07:00
|
|
|
|
|
|
|
const defaultState: UseDimensionsRect = {
|
|
|
|
width: 0,
|
|
|
|
height: 0,
|
|
|
|
};
|
|
|
|
|
|
|
|
const useDimensions = (): UseDimensionsResult => {
|
2022-07-18 10:36:56 -07:00
|
|
|
const [element, setRef] = useState<Element | null>(null);
|
2022-06-22 06:25:46 -07:00
|
|
|
const [rect, setRect] = useState<UseDimensionsRect>(defaultState);
|
|
|
|
|
|
|
|
const observer = useMemo(
|
|
|
|
() =>
|
2022-08-31 11:32:13 -07:00
|
|
|
new ResizeObserver((entries: any) => {
|
2022-06-22 06:25:46 -07:00
|
|
|
if (entries[0]) {
|
|
|
|
const { width, height } = entries[0].contentRect;
|
|
|
|
setRect({ width, height });
|
|
|
|
}
|
|
|
|
}),
|
|
|
|
[],
|
|
|
|
);
|
|
|
|
|
|
|
|
useEffect((): any => {
|
2023-01-05 14:56:05 -08:00
|
|
|
if (!element) return;
|
2022-06-22 06:25:46 -07:00
|
|
|
observer.observe(element);
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
observer.disconnect();
|
|
|
|
};
|
|
|
|
}, [element]);
|
|
|
|
|
2022-07-18 10:36:56 -07:00
|
|
|
return [element, setRef, rect];
|
2022-06-22 06:25:46 -07:00
|
|
|
};
|
|
|
|
|
|
|
|
export { useDimensions };
|