Open History to see the last commit
1import { useLayoutEffect, useState } from "react";
2
3export function useElementWidth<T extends HTMLElement>() {
4 const [element, setElement] = useState<T | null>(null);
5 const [width, setWidth] = useState<number | null>(null);
6
7 useLayoutEffect(() => {
8 if (!element) return;
9
10 const update = (nextWidth: number) => {
11 setWidth((currentWidth) => (currentWidth === nextWidth ? currentWidth : nextWidth));
12 };
13
14 update(element.getBoundingClientRect().width);
15 if (typeof ResizeObserver === "undefined") return;
16
17 const observer = new ResizeObserver(([entry]) => {
18 if (entry) update(entry.contentRect.width);
19 });
20 observer.observe(element);
21 return () => observer.disconnect();
22 }, [element]);
23
24 return [setElement, width] as const;
25}