useResizeObserver
Raw ResizeObserver binding.
Import
TypeScript
import { useResizeObserver } from '@/hooks';API
Signature
useResizeObserver(ref, onResize?) → { width, height }
When to use
Use useResizeObserver 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 · useResizeObserverEditor
function Observed() { const ref = useRef<HTMLDivElement>(null); const size = useResizeObserver(ref, ({ width }) => console.log(width)); return <div ref={ref}>{size.width}</div>; }
Preview
Implementation source
Full library source for useResizeObserver — copy into your project when you are not installing a package yet.
hooks/dom/useResizeObserver.ts
import { useEffect, useRef, useState } from 'react';
import type { RefObject } from 'react';
import { isBrowser } from '../utility/isBrowser';
import { useLatest } from '../utility/useLatest';
export interface ResizeObserverEntryLike {
width: number;
height: number;
entry: ResizeObserverEntry;
}
/**
* Observe element size via ResizeObserver.
* Returns the latest content box size.
*/
export function useResizeObserver<T extends Element>(
target: RefObject<T | null>,
onResize?: (size: ResizeObserverEntryLike) => void,
): { width: number; height: number } {
const [size, setSize] = useState({ width: 0, height: 0 });
const onResizeRef = useLatest(onResize);
const frame = useRef<number | null>(null);
useEffect(() => {
if (!isBrowser() || typeof ResizeObserver === 'undefined') return;
const el = target.current;
if (!el) return;
const observer = new ResizeObserver((entries) => {
const entry = entries[0];
if (!entry) return;
const { width, height } = entry.contentRect;
if (frame.current !== null) cancelAnimationFrame(frame.current);
frame.current = requestAnimationFrame(() => {
setSize({ width, height });
onResizeRef.current?.({ width, height, entry });
});
});
observer.observe(el);
return () => {
if (frame.current !== null) cancelAnimationFrame(frame.current);
observer.disconnect();
};
}, [target, onResizeRef]);
return size;
}
Copy-paste example
useResizeObserver.example.tsx
'use client';
import { useRef } from 'react';
import { useResizeObserver } from '@/hooks';
export function Observed() {
const ref = useRef<HTMLDivElement>(null);
const size = useResizeObserver(ref, ({ width }) => console.log(width));
return <div ref={ref}>{size.width}</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/useResizeObserver.tsfor implementation details