Skip to main content

useBoundingRect

function useBoundingRect(
element,
updateOnWindowResize,
windowResizeThrottle): DOMRect | undefined;

Observes a HTMLElement and returns its bounding rect. Updates when the element's size changes.

If a ref to a HTMLElement is passed and ref.current is null it polls the ref to detect when the HTMLElement value gets assigned to ref.current, this is useful in case the Component using this hook does not rerender when ref.current changes.

Parameters​

ParameterTypeDefault valueDescription
elementHTMLElement | RefObject<HTMLElementnull>` \null | undefined
updateOnWindowResizebooleanfalseWhether to update the rect on window resize (default: false)
windowResizeThrottlenumber0Throttle interval in ms for window resize updates (default: 0)

Returns​

DOMRect | undefined

The DOMRect of the element, or undefined if element is not available

Example​

const ref = useRef<HTMLDivElement>(null);
const rect = useBoundingRect(ref);

const [element, setElement] = useState<HTMLDivElement | null>(null);
const rect2 = useBoundingRect(element);

// Update on window resize with 150ms throttle
const rect3 = useBoundingRect(ref, true, 150);