useBoundingclientrectRef
Supplies a callback ref, its current DOMRect, and a manual measurement function.
About
useBoundingclientrectRef owns the ref used to measure an element. It is useful when the observed node may be attached conditionally or replaced and when the caller also needs an explicit update() operation.
Example
import { useBoundingclientrectRef } from "rooks";
export default function MeasuredPanel() {
const [panelRef, rect, update] = useBoundingclientrectRef();
return (
<section>
<div
ref={panelRef}
style={{
width: "60%",
minWidth: 180,
border: "1px solid",
padding: 12,
}}
>
Width: {rect ? `${Math.round(rect.width)}px` : "measuring"}
</div>
<button type="button" onClick={() => update()}>
Measure now
</button>
</section>
);
}Parameters
This hook accepts no parameters.
Return value
Returns [ref, rect, update]:
refis the callback ref to attach to anHTMLElement.rectis that element'sDOMRect, ornullbefore attachment and after detachment.update()immediately rereadsgetBoundingClientRect()for the current node and returnsvoid.
Behavior and lifecycle
Attaching or replacing the node triggers an initial measurement. The hook merges its measuring ref with a mutation-observer ref configured for attributes, character data, child lists, and the full subtree. A reported mutation invokes update(). Detaching the node resets the rect to null, and the observer disconnects on node changes and unmount.
The observer watches DOM mutations, not viewport scroll or every source of layout change. Call update() after a known external layout change, or choose a resize-based hook when element-size changes are the primary signal.
Compatibility and accessibility
The server and pre-attachment value is null; browser APIs are used only from effects after a node exists. MutationObserver and getBoundingClientRect() must be available in the client environment.
Measurement is presentational and should not replace semantic markup. Keep layouts usable under zoom, font scaling, and content reflow. See SSR and browser APIs.
Related
- useBoundingclientrect accepts an object ref instead.
- useDimensionsRef responds to window resize and scroll.
- useMeasure observes element-size changes with
ResizeObserver.