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:
| Option | Type | Default | Description |
|---|---|---|---|
updateOnResize | boolean | true | Remeasure after window resize events. |
updateOnScroll | boolean | true | Remeasure after window scroll events. |
Return value
Returns [ref, dimensions, element].
refattaches to anHTMLDivElement.dimensionsisnullbefore the first measurement, then containstop,right,bottom,left,width,height,x, andy. Thexandyfields mirrorleftandtop.elementis the currently attachedHTMLElement, ornull.
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.
Related
- useMeasure observes element-size changes rather than window events.
- useBoundingclientrectRef exposes a manual bounding-rect update.
- useWindowSize reports viewport dimensions.