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 resize and scroll events by default. Both behaviors can be disabled via windowResize and windowScroll options.
  • SSR-safe: Returns zero values during server-side rendering. Set immediate: false to defer the first measurement until you explicitly call update().
  • See also useElementSize and useMeasure for tracking only width/height via ResizeObserver, and useWindowSize for 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

ArgumentDescriptionTypeDefaultValue
targettarget elementBasicTarget<Element> (Required)-
optionsoptional paramsUseElementBoundingOptions | undefined-

UseElementBoundingOptions

PropertyDescriptionTypeDefaultValue
resetReset values to 0 on component unmountedbooleantrue
windowResizeListen to window resize eventbooleantrue
windowScrollListen to window scroll eventbooleantrue
immediateImmediately call update on component mountedboolean-

UseElementBoundingReturn

PropertyDescriptionTypeDefaultValue
heightHeight of the elementnumber (Required)-
bottomBottom position of the elementnumber (Required)-
leftLeft position of the elementnumber (Required)-
rightRight position of the elementnumber (Required)-
topTop position of the elementnumber (Required)-
widthWidth of the elementnumber (Required)-
xX position of the elementnumber (Required)-
yY position of the elementnumber (Required)-
updateManual 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;