useMeasure
Layout & observersReactively measure an element's bounds — size and viewport position — via ResizeObserver
Install
$ npm install @usefy/use-measureQuick start
import { useMeasure } from "@usefy/use-measure";
function Card() {
const [ref, bounds] = useMeasure<HTMLDivElement>();
return (
<div ref={ref} style={{ resize: "both", overflow: "auto" }}>
{Math.round(bounds.width)} × {Math.round(bounds.height)}
<br />
at ({Math.round(bounds.x)}, {Math.round(bounds.y)})
</div>
);
}API reference
useMeasure<T extends Element = Element>(): [ref, bounds]
Returns a tuple:
| Index | Name | Type | Description |
|---|---|---|---|
0 | ref | (element: T | null) => void | Callback ref to attach to the element you want to measure |
1 | bounds | Bounds | The element's current bounds (all-zero until measured) |
Bounds
Mirrors the shape of a DOMRect. width / height are the rendered size; the rest are positions relative to the viewport (as reported by getBoundingClientRect()).
| Field | Type | Description |
|---|---|---|
x | number | Left edge, relative to the viewport |
y | number | Top edge, relative to the viewport |
width | number | Rendered width in pixels |
height | number | Rendered height in pixels |
top | number | Distance from viewport top to the top edge |
right | number | Distance from viewport left to the right edge |
bottom | number | Distance from viewport top to the bottom edge |
left | number | Distance from viewport left to the left edge |
Also exported: EMPTY_BOUNDS (the frozen all-zero bounds used as the initial / SSR value) and the Bounds, UseMeasureRef, and UseMeasureReturn types.
Note: bounds come from
getBoundingClientRect(), so they update on resize (viaResizeObserver), not on scroll — scrolling does not change an element's size. If you need scroll-driven position tracking, re-measure on scroll separately.
Go deeper
This page is the quick reference. For every example, prop, and edge case, read the full README — or open Storybook to change props live.