Skip to content
usefy

useMeasure

Layout & observers

Reactively measure an element's bounds — size and viewport position — via ResizeObserver

Install

$ npm install @usefy/use-measure

Quick start

useMeasure.tsx
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:

IndexNameTypeDescription
0ref(element: T | null) => voidCallback ref to attach to the element you want to measure
1boundsBoundsThe 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()).

FieldTypeDescription
xnumberLeft edge, relative to the viewport
ynumberTop edge, relative to the viewport
widthnumberRendered width in pixels
heightnumberRendered height in pixels
topnumberDistance from viewport top to the top edge
rightnumberDistance from viewport left to the right edge
bottomnumberDistance from viewport top to the bottom edge
leftnumberDistance 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 (via ResizeObserver), 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.

More in layout & observers