Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

1.3 KB
Raw Blame
import { useEffect, useLayoutEffect, useState } from 'react';
import debounce from 'lodash-es/debounce';

export type Dimensions = {
	width: number;
	height: number;
};

export function useResizeObserver<T extends HTMLElement>(
	ref: React.RefObject<T>,
	debounceTime = 300,
): Dimensions {
	const [size, setSize] = useState<Dimensions>({
		width: ref.current?.clientWidth || 0,
		height: ref.current?.clientHeight || 0,
	});

	// Measure before paint so the first frame has real dimensions, not 0 (the
	// debounced observer below only catches up after paint → layout jump).
	useLayoutEffect(() => {
		const node = ref.current;
		if (node) {
			setSize({ width: node.clientWidth, height: node.clientHeight });
		}
	}, [ref]);

	useEffect(() => {
		const handleResize = debounce(
			(entries: ResizeObserverEntry[]) => {
				const entry = entries[0];
				if (entry) {
					const { width, height } = entry.contentRect;
					setSize({ width, height });
				}
			},
			debounceTime,
			{
				leading: true,
			},
		);

		const ro = new ResizeObserver(handleResize);
		const referenceNode = ref.current;
		if (referenceNode) {
			ro.observe(referenceNode);
		}

		return (): void => {
			if (referenceNode) {
				ro.disconnect();
			}
		};
	}, [ref, debounceTime]);

	return size;
}