useElementSize
Width and height via ResizeObserver.
Import
TypeScript
import { useElementSize } from '@/hooks';API
Signature
useElementSize(ref) → { width, height }
When to use
Use useElementSize instead of re-implementing the same pattern in multiple components.
SSR / Next.js
Measurements are 0 / empty until the element is mounted.
Live playground
Edit the example and see it run against the real @/hooks package in this app.
Live playgroundEdit · run with real
@/hooks · useElementSizeEditor
function Box() { const ref = useRef<HTMLDivElement>(null); const { width, height } = useElementSize(ref); return <div ref={ref}>Size: {Math.round(width)}×{Math.round(height)}</div>; }
Preview
Implementation source
Full library source for useElementSize — copy into your project when you are not installing a package yet.
hooks/dom/useElementSize.ts
import type { RefObject } from 'react';
import { useResizeObserver } from './useResizeObserver';
/** Element width/height via ResizeObserver. */
export function useElementSize<T extends Element>(
ref: RefObject<T | null>,
): { width: number; height: number } {
return useResizeObserver(ref);
}
Copy-paste example
useElementSize.example.tsx
'use client';
import { useRef } from 'react';
import { useElementSize } from '@/hooks';
export function Box() {
const ref = useRef<HTMLDivElement>(null);
const { width, height } = useElementSize(ref);
return <div ref={ref}>Size: {Math.round(width)}×{Math.round(height)}</div>;
}Production checklist
- Called only from Client Components or other custom hooks
- Type parameters filled in (e.g.
useFetch<User[]>) - Tip: Attach the ref before measuring. ResizeObserver requires a mounted element.
- Source of truth: open
hooks/dom/useElementSize.tsfor implementation details