All hooks / Elements
useElementSize
An element's size in CSS pixels, updated whenever it resizes. By default the content box (excluding padding and border); pass { box: 'border-box' } to include them, e.g. to match getBoundingClientRect() without transforms.
Returns a callback ref to put on the element. The size is { width: 0, height: 0 } on the server and until the element is measured. Measurement starts in a layout effect, so in the browser the real size is usually ready before the first paint.
Import
import { useElementSize } from '@vincent.ri/react-tils'
// or only this hook
import { useElementSize } from '@vincent.ri/react-tils/useElementSize'Usage
const [ref, { width, height }] = useElementSize<HTMLDivElement>()
return (
<div ref={ref} style={{ height: 300 }}>
<Chart width={width} height={height} />
</div>
)Live demo
The box reports its own width.
When to use it
JS needs an element's pixel size, e.g. sizing a canvas or chart to its container, or choosing how many items fit in a row.
When not to
Only styles depend on the size; use CSS container queries, which need no JS. For the window, use useWindowSize.
API
function useElementSize<T extends Element = HTMLElement>(options?: ElementSizeOptions): [(element: T | null) => void, ElementSize]| Parameter | Description |
|---|---|
options | box: which box to measure. Default 'content-box'. |
Returns [ref, size]. Pass ref to the element's ref prop.
Types
export type ElementSize = {
width: number;
height: number;
};
export type ElementSizeOptions = {
/** `'content-box'` (default) excludes padding and border; `'border-box'` includes them. */
box?: "content-box" | "border-box";
};Browser support
| Uses | Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS |
|---|---|---|---|---|---|---|
| ResizeObserverWidely available | 64+ | 79+ | 69+ | 13.1+ | 64+ | 13.4+ |
First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).
Coming from another library?
Other libraries call this useMeasure, useSize, useResizeObserver.