useResizeObserver
useResizeObserver wraps the browser ResizeObserver API with the conventions used throughout this library: SSR-safe, no resubscription on callback identity changes, and an enabled flag for toggling observation without unmounting.
Live preview
Import
import { useResizeObserver } from 'entangle-ui';Signature
function useResizeObserver<T extends HTMLElement>( ref: React.RefObject<T | null>, callback: (entry: ResizeObserverEntry) => void, options?: UseResizeObserverOptions): void;
interface UseResizeObserverOptions { enabled?: boolean;}Usage
function Box() { const ref = useRef<HTMLDivElement>(null); const [width, setWidth] = useState(0);
useResizeObserver(ref, entry => { setWidth(entry.contentRect.width); });
return <div ref={ref}>Width: {width}px</div>;}API
| Prop | Type | Default | Description |
|---|---|---|---|
ref * | RefObject<T | null> | — | Ref pointing to the element you want to observe. |
callback * | (entry: ResizeObserverEntry) => void | — | Called for each observed entry on every size change. Does not need to be memoized — the hook stores it in a ref so the underlying observer never resubscribes when the callback identity changes. |
options.enabled | boolean | true | When false, the observer is detached. Toggling between true and false attaches / disconnects without unmounting the host component. |
Returns
void. The hook owns its ResizeObserver instance internally and disconnects it on unmount or when the ref / enabled changes.
Common pitfalls
- SSR safety: the hook checks
typeof ResizeObserver === 'undefined'and silently no-ops on the server, in tests without a polyfill, or in legacy browsers without the API. - Single-target only: each call observes exactly one element. To observe multiple elements (e.g. a viewport and its first child), call the hook twice with different refs.
contentRectvsborderBoxSize: the entry exposes both.contentRectis the most common shape for layout work; switch toborderBoxSize[0]if you need the border-box dimensions.- Initial measurement:
ResizeObserverfires once on attach with the element’s current size, so you do not need a separategetBoundingClientRect()call to seed initial state — unless you want the value before the first paint.