Skip to main content
useSize is a hook that tracks the dimensions of an HTML element, automatically updating when the element is resized. It uses the ResizeObserver API to efficiently monitor size changes.

Installation

Function Signature

Parameters

HTMLElement | null
required
The HTML element to observe for size changes. When null, the hook returns undefined.

Return Value

{ width: number; height: number } | undefined
An object containing the element’s width and height in pixels, or undefined if no element is provided.

Usage

Basic Example

With useRef

Responsive Component

Tracking Container Changes

Implementation Details

The hook:
  1. Provides the initial size immediately using offsetWidth and offsetHeight
  2. Creates a ResizeObserver to watch for size changes
  3. Uses the borderBoxSize API when available for more accurate measurements
  4. Falls back to offsetWidth/offsetHeight for older browsers
  5. Observes the element with box: 'border-box' to include borders and padding
  6. Cleans up the observer when the element changes or component unmounts
  7. Returns undefined when the element becomes null

Browser Compatibility

This hook uses the ResizeObserver API, which is supported in all modern browsers. For older browsers, you may need a polyfill.

Notes

The hook uses useLayoutEffect to set the initial size as early as possible and set up the ResizeObserver, ensuring measurements are taken before the browser paints.
The size is measured using the border box, which includes the element’s content, padding, and border, but not its margin.
The hook handles browser inconsistencies by checking for borderBoxSize support and falling back to offsetWidth/offsetHeight when necessary.