Skip to Content
ohooks

useElementSize

Tracks the width and height of a DOM element reactively using ResizeObserver.

Loading preview...

The useElementSize hook observes a target DOM element with ResizeObserver and returns its live { width, height } dimensions.

Installation

pnpm dlx shadcn@latest add https://ohooks.vercel.app/r/useElementSize.json

Usage

Examples

Responsive Component Layout

Adapt a component's layout based on its own container width rather than the global viewport size.

Selecting the Box Model and Initial Size

Specify box: "border-box" to include padding and borders, and initialSize to provide fallback dimensions before the element mounts.

API Reference

UseElementSizeOptions

Configuration options for ResizeObserver box model and initial dimensions.

Property
Specification
initialWidth?
numberdefault:0
Initial width used during SSR and before the first measurement
initialHeight?
numberdefault:0
Initial height used during SSR and before the first measurement
box?
union
enabled?
uniondefault:true
Whether the ResizeObserver is active

ElementSize

Dimensions object returned by the hook.

Property
Specification
widthrequired
number
Measured width of the element in pixels
heightrequired
number
Measured height of the element in pixels