Rooks
HooksUI & Layout

useDimensionsRef

Measures an attached div after layout and optionally on window resize and scroll.

About

useDimensionsRef returns a callback ref and a simplified bounding-rect snapshot. It schedules measurement in requestAnimationFrame after layout, on attachment, and—by default—after window resize and scroll events.

Example

import { useDimensionsRef } from "rooks";

export default function PositionedPanel() {
  const [panelRef, dimensions] = useDimensionsRef();

  return (
    <section>
      <div
        ref={panelRef}
        style={{ width: "50%", padding: 16, border: "1px solid" }}
      >
        Resize or scroll the window.
      </div>
      <p aria-live="polite">
        {dimensions
          ? `${Math.round(dimensions.width)} × ${Math.round(dimensions.height)} at ${Math.round(dimensions.left)}, ${Math.round(dimensions.top)}`
          : "Waiting for a client-side measurement"}
      </p>
    </section>
  );
}

Parameters

The optional object contains:

OptionTypeDefaultDescription
updateOnResizebooleantrueRemeasure after window resize events.
updateOnScrollbooleantrueRemeasure after window scroll events.

Return value

Returns [ref, dimensions, element].

  • ref attaches to an HTMLDivElement.
  • dimensions is null before the first measurement, then contains top, right, bottom, left, width, height, x, and y. The x and y fields mirror left and top.
  • element is the currently attached HTMLElement, or null.

During server rendering the tuple is [undefined, null, null].

Behavior and lifecycle

Node attachment changes schedule a measurement from a layout effect. Enabled resize and scroll listeners schedule the same work through requestAnimationFrame; their listeners are cleaned up by the underlying window-event hooks. This coalesces reads with a browser frame but does not cancel an already queued frame when the component unmounts.

The hook reads getBoundingClientRect(), so positions are relative to the viewport and change with scrolling. Disable either listener when that signal is unnecessary.

Compatibility and accessibility

The hook explicitly detects a missing window, logs a warning, and returns its server tuple. Client and server markup should not depend on a non-null first measurement. Browsers must provide requestAnimationFrame() and getBoundingClientRect().

Use dimensions for progressive layout enhancements rather than hiding essential content. Verify behavior at high zoom and with larger text. See SSR and browser APIs.

On this page