useSize
useSize is a custom hook to track the size and position of an HTML element in real-time.
Usage
import { useSize } from "hookify-react";
export default function UseSizeExample() {
const { ref, size } = useSize<HTMLDivElement>();
return (
<div ref={ref} style={{ padding: "20px", border: "1px solid black", resize: "both", overflow: "auto" }}>
{size ? (
<>
<p>Width: {size.width.toFixed(0)}px</p>
<p>Height: {size.height.toFixed(0)}px</p>
<p>Top: {size.top.toFixed(0)} / Left: {size.left.toFixed(0)}</p>
<p>Bottom: {size.bottom.toFixed(0)} / Right: {size.right.toFixed(0)}</p>
</>
) : (
<p>Measuring...</p>
)}
</div>
);
}
API Reference
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| None | - | - | This hook does not take any parameters. Attach the returned ref to the element you want to measure. |
Return Value
| Property | Type | Description |
|---|---|---|
ref | React.MutableRefObject<T | null> | A ref to attach to the element whose size should be tracked. |
size | { width: number; height: number; top: number; left: number; bottom: number; right: number } | null | The element's current dimensions and position, or null before the first measurement. |
Behavior
- Tracks the element attached to
refin real time using aResizeObserver. - Returns
nulluntil the first measurement is taken, then exposeswidth,height,top,left,bottom, andright. - Provides an immediate measurement via
getBoundingClientRectbefore the firstResizeObservercallback fires. - Guards against missing
ResizeObserversupport and server-side rendering (no-ops when unavailable). - Disconnects the
ResizeObserveron unmount.