# 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

```ts
import { useElementSize } from '@vincent.ri/react-tils'
// or only this hook
import { useElementSize } from '@vincent.ri/react-tils/useElementSize'
```

## Usage

```ts
const [ref, { width, height }] = useElementSize<HTMLDivElement>()
return (
  <div ref={ref} style={{ height: 300 }}>
    <Chart width={width} height={height} />
  </div>
)
```

## 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

```ts
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

```ts
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

Works in all modern browsers.

## Coming from another library?

Other libraries call this `useMeasure`, `useSize`, `useResizeObserver`.

---

322 B minified and brotlied
Source: https://github.com/vincentri/react-tils/blob/main/src/useElementSize.ts
Docs page: https://vincentri.github.io/react-tils/hooks/useElementSize/
Previous: [useScrollProgress](https://vincentri.github.io/react-tils/hooks/useScrollProgress.md)
Next: [useElementScroll](https://vincentri.github.io/react-tils/hooks/useElementScroll.md)
