summaryrefslogtreecommitdiff
path: root/apps/web/src/hooks/use-container-size.ts
blob: 8b46f20ea7f3c1dfb20eba3aba5107e90af8682b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { useEffect, useState } from "react";

export function useContainerSize({
	containerRef,
}: {
	containerRef: React.RefObject<HTMLElement | null>;
}) {
	const [size, setSize] = useState({ width: 0, height: 0 });

	useEffect(() => {
		const container = containerRef.current;
		if (!container) return;

		const observer = new ResizeObserver((entries) => {
			for (const entry of entries) {
				const { width, height } = entry.contentRect;
				setSize({ width, height });
			}
		});

		observer.observe(container);

		return () => {
			observer.disconnect();
		};
	}, [containerRef]);

	return size;
}