Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

use-element-width.ts

24 lines788 Bytes

1import { useLayoutEffect, useRef, useState } from "react";
2​
3/**
4 * Tracks an element's width with a ResizeObserver. Used for layout decisions
5 * that depend on the app pane (which the user can resize), not the window.
6 * Returns `null` until the first measurement.
7 */
8export function useElementWidth<T extends HTMLElement>() {
9 const ref = useRef<T>(null);
10 const [width, setWidth] = useState<number | null>(null);
11​
12 useLayoutEffect(() => {
13 const element = ref.current;
14 if (!element) return;
15 setWidth(element.getBoundingClientRect().width);
16 const observer = new ResizeObserver(([entry]) => {
17 if (entry) setWidth(entry.contentRect.width);
18 });
19 observer.observe(element);
20 return () => observer.disconnect();
21 }, []);
22​
23 return [ref, width] as const;