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
The HTML element to observe for size changes. When
null, the hook returns undefined.Return Value
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:- Provides the initial size immediately using
offsetWidthandoffsetHeight - Creates a
ResizeObserverto watch for size changes - Uses the
borderBoxSizeAPI when available for more accurate measurements - Falls back to
offsetWidth/offsetHeightfor older browsers - Observes the element with
box: 'border-box'to include borders and padding - Cleans up the observer when the element changes or component unmounts
- Returns
undefinedwhen the element becomesnull
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.