Skip to main content

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

ParameterTypeDefaultDescription
None--This hook does not take any parameters. Attach the returned ref to the element you want to measure.

Return Value

PropertyTypeDescription
refReact.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 } | nullThe element's current dimensions and position, or null before the first measurement.

Behavior

  • Tracks the element attached to ref in real time using a ResizeObserver.
  • Returns null until the first measurement is taken, then exposes width, height, top, left, bottom, and right.
  • Provides an immediate measurement via getBoundingClientRect before the first ResizeObserver callback fires.
  • Guards against missing ResizeObserver support and server-side rendering (no-ops when unavailable).
  • Disconnects the ResizeObserver on unmount.