useMeasure
React sensor hook that tracks dimensions of an HTML element using the Resize Observer API
useMeasure tracks the full dimensions of a DOM element using the ResizeObserver API. It returns a tuple of [rect, stop] where rect is a DOMRect-like object containing x, y, width, height, top, right, bottom, and left, and stop is a function to disconnect the observer. Pass a ref to the element and optional ResizeObserverOptions.
When to Use
- Measuring element dimensions for layout calculations that need full bounding-box data
- Building responsive containers that adjust internal layout based on their own size
- Tracking size changes in dynamically resizable components like text editors or split panes
Notes
- SSR-safe: Returns zeroed-out rect values during server-side rendering. Observation begins after mount.
- Stoppable: Call the returned
stopfunction to disconnect the ResizeObserver when measurement is no longer needed. - See also
useElementSizefor a simpler[width, height]tuple,useElementBoundingfor position-aware measurements viagetBoundingClientRect, anduseResizeObserverfor direct access to the raw ResizeObserver callback.
Usage
Live Editor
function Demo() { const ref = useRef<HTMLTextAreaElement>(null); const [rect, stop] = useMeasure(ref); return ( <div> <div>Resize the box to see changes</div> <div> <button onClick={() => stop()}>stop observe</button> </div> <br /> <textarea ref={ref} disabled style={{ width: 286, height: 166 }} value={JSON.stringify(rect, null, 2)} /> </div> ); };
Result
API
useMeasure
Returns
readonly [UseMeasureRect, () => void]: [DOMRect, stop listening function]
Arguments
| Argument | Description | Type | DefaultValue |
|---|---|---|---|
| target | dom element | BasicTarget<Element> (Required) | - |
| options | optional params | ResizeObserverOptions | undefined | - |
UseMeasureRect
| Property | Description | Type | DefaultValue |
|---|---|---|---|
| top | MDN Reference | number (Required) | - |
| bottom | MDN Reference | number (Required) | - |
| left | MDN Reference | number (Required) | - |
| right | MDN Reference | number (Required) | - |
| height | MDN Reference | number (Required) | - |
| width | MDN Reference | number (Required) | - |
| x | MDN Reference | number (Required) | - |
| y | MDN Reference | number (Required) | - |
BasicTarget
export type BasicTarget<T extends TargetType = Element> = (() => TargetValue<T>) | TargetValue<T> | MutableRefObject<TargetValue<T>>;
TargetValue
type TargetValue<T> = T | undefined | null;
TargetType
type TargetType = HTMLElement | Element | Window | Document | EventTarget;