useSize
Reads width and height from ResizeObserver.
Reads width and height from ResizeObserver.
Import
import { useSize } from '@kamod-ch/hooks'Live demo
Basic demo
Reads width and height from ResizeObserver.
Browser-only demo
This demo starts after the page mounts in the browser.
import { useRef, useState } from 'preact/hooks'
import { useSize } from '@kamod-ch/hooks'
export default function UseSizeDemo() {
const ref = useRef<HTMLDivElement>(null)
const [width, setWidth] = useState(220)
const size = useSize(ref)
return (
<div>
<input type="range" min={160} max={360} value={width} onInput={(event) => setWidth(Number(event.currentTarget.value))} />
<div ref={ref} class="demo-target-box" style={{ width: width + 'px' }}>Observed box</div>
<p><strong>Measured size:</strong> {size?.width ?? 0} × {size?.height ?? 0}</p>
</div>
)
}
API
TypeScript signature
import type { BasicTarget } from '../utils/domTarget.js';
type Size = {
width: number;
height: number;
};
declare function useSize(target: BasicTarget): Size | undefined;
export default useSize;
/SSR considerations
This hook touches browser APIs. Render it after mount or guard it with BrowserOnly in SSR and static builds.
Browser compatibility
Requires the corresponding browser API to exist in the current environment.