useElementMeasure

PHOTO EMBED

Wed Sep 15 2021 07:19:48 GMT+0000 (UTC)

Saved by @cxgarcia #typescript

const useElementMeasure = (
	elRef: React.RefObject<any>,
	effectDeps: unknown[] = []
) => {
	const [{ width, height }, setMeasure] = useState(() => {
		const element = elRef?.current;

		return {
			width: element ? element.clientWidth : 0,
			height: element ? element.clientHeight : 0,
		};
	});

	const measure = useCallback(() => {
		const element = elRef?.current;
		if (!element) {
			return;
		}

		setMeasure({
			width: element.clientWidth,
			height: element.clientHeight,
		});

	}, [elRef, ...effectDeps]);

	useEffect(() => {
		measure();

		window.addEventListener("resize", measure);

		return () => {
			window.removeEventListener("resize", measure);
		};
	}, [measure]);

	return [width, height];
}
content_copyCOPY