concept-collection / timeseries-compressibility
timeseries-compressibility / src / components / useWidth.ts
16 lines · 549 BBlameHistoryRaw
1import { useLayoutEffect, useState, type RefObject } from 'react'
3/** The rendered width of a container, tracked through resizes. */
4export function useWidth(ref: RefObject<HTMLElement | null>, fallback = 480): number {
5 const [width, setWidth] = useState(fallback)
6 useLayoutEffect(() => {
7 const el = ref.current
8 if (!el) return
9 const update = () => setWidth(el.clientWidth || fallback)
10 update()
11 const ro = new ResizeObserver(update)
12 ro.observe(el)
13 return () => ro.disconnect()
14 }, [ref, fallback])
15 return width