useMeasure
Full getBoundingClientRect.
Import
TypeScript
import { useMeasure } from '@/hooks';API
Signature
useMeasure(ref) → MeasureRect
When to use
Use useMeasure 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 · useMeasureEditor
function Measured() { const ref = useRef<HTMLDivElement>(null); const rect = useMeasure(ref); return <div ref={ref}>top={rect.top} left={rect.left}</div>; }
Preview
Implementation source
Full library source for useMeasure — copy into your project when you are not installing a package yet.
hooks/dom/useMeasure.ts
import { useCallback, useState } from 'react';
import type { RefObject } from 'react';
import { useResizeObserver } from './useResizeObserver';
import { isBrowser } from '../utility/isBrowser';
import { useIsomorphicLayoutEffect } from '../utility/useIsomorphicLayoutEffect';
export interface MeasureRect {
x: number;
y: number;
width: number;
height: number;
top: number;
left: number;
bottom: number;
right: number;
}
const empty: MeasureRect = {
x: 0,
y: 0,
width: 0,
height: 0,
top: 0,
left: 0,
bottom: 0,
right: 0,
};
/** Full bounding rect measurement for an element. */
export function useMeasure<T extends HTMLElement>(
ref: RefObject<T | null>,
): MeasureRect {
const [rect, setRect] = useState<MeasureRect>(empty);
const measure = useCallback(() => {
if (!isBrowser() || !ref.current) return;
const r = ref.current.getBoundingClientRect();
setRect({
x: r.x,
y: r.y,
width: r.width,
height: r.height,
top: r.top,
left: r.left,
bottom: r.bottom,
right: r.right,
});
}, [ref]);
useResizeObserver(ref, measure);
useIsomorphicLayoutEffect(() => {
measure();
}, [measure]);
return rect;
}
Copy-paste example
useMeasure.example.tsx
'use client';
import { useRef } from 'react';
import { useMeasure } from '@/hooks';
export function Measured() {
const ref = useRef<HTMLDivElement>(null);
const rect = useMeasure(ref);
return <div ref={ref}>top={rect.top} left={rect.left}</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/useMeasure.tsfor implementation details