useElementBounding
React Element Hook that tracks bounding box of an HTML element
useElementBounding reactively tracks the bounding rectangle of a DOM element using getBoundingClientRect(). It returns an object containing x, y, top, bottom, left, right, width, height, and an update() function for manual re-measurement. By default it automatically recalculates on window scroll and resize.
When to Use
- Positioning tooltips, popovers, or floating elements relative to a target element
- Implementing collision detection or overlap checks between UI elements
- Tracking element position for scroll-linked animations or parallax effects
Notes
- Reactivity: Automatically updates on window
resizeandscrollevents by default. Both behaviors can be disabled viawindowResizeandwindowScrolloptions. - SSR-safe: Returns zero values during server-side rendering. Set
immediate: falseto defer the first measurement until you explicitly callupdate(). - See also
useElementSizeanduseMeasurefor tracking only width/height via ResizeObserver, anduseWindowSizefor viewport dimensions.
Usage
Live Editor
function Demo() { const ref = useRef<HTMLTextAreaElement>(null); const rect = useElementBounding(ref); return ( <div> <p> Resize the box to see changes</p> <textarea ref={ref} readOnly value={JSON.stringify(rect, null, 2)} /> </div> ); };
Result
API
useElementBounding
Returns
UseElementBoundingReturn
Arguments
| Argument | Description | Type | DefaultValue |
|---|---|---|---|
| target | target element | BasicTarget<Element> (Required) | - |
| options | optional params | UseElementBoundingOptions | undefined | - |
UseElementBoundingOptions
| Property | Description | Type | DefaultValue |
|---|---|---|---|
| reset | Reset values to 0 on component unmounted | boolean | true |
| windowResize | Listen to window resize event | boolean | true |
| windowScroll | Listen to window scroll event | boolean | true |
| immediate | Immediately call update on component mounted | boolean | - |
UseElementBoundingReturn
| Property | Description | Type | DefaultValue |
|---|---|---|---|
| height | Height of the element | number (Required) | - |
| bottom | Bottom position of the element | number (Required) | - |
| left | Left position of the element | number (Required) | - |
| right | Right position of the element | number (Required) | - |
| top | Top position of the element | number (Required) | - |
| width | Width of the element | number (Required) | - |
| x | X position of the element | number (Required) | - |
| y | Y position of the element | number (Required) | - |
| update | Manual update | () => void (Required) | - |
BasicTarget
export type BasicTarget<T extends TargetType = Element> = (() => TargetValue<T>) | TargetValue<T> | MutableRefObject<TargetValue<T>>;
TargetValue
type TargetValue<T> = T | undefined | null;
TargetType
type TargetType = HTMLElement | Element | Window | Document | EventTarget;