bigbuffet-rw/app/soapbox/hooks/useDimensions.ts

39 lines
904 B
TypeScript
Raw Normal View History

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(
() =>
new (window as any).ResizeObserver((entries: any) => {
if (entries[0]) {
const { width, height } = entries[0].contentRect;
setRect({ width, height });
}
}),
[],
);
useEffect((): any => {
if (!element) return null;
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 };