Resize Observer
Resize Observer delivers element-level size changes as frame-batched callbacks, replacing window resize handlers plus getBoundingClientRect polling for responsive components.
Definition
Resize Observer watches elements for size changes and invokes an asynchronous callback with the new content box, border box, and device pixel size. It fires after layout and before paint, batching multiple observations per frame and exposing an error-free way to build components that adapt to their own box rather than the viewport.
Context and scope
Used for container-query-like behaviors, charts that resize to their slot, virtualized grids, and media players sizing to their wrapper. Replaces debounce-heavy window resize logic.
Common misconceptions
- It watches the viewport — it observes individual elements, catching size changes from layout, not just window resizes
- Callbacks fire before paint — they run after layout and before paint, and mutating styles can cause a resize loop
- It duplicates window resize events — window resizes only account for a subset of the size changes an element experiences
Anti-patterns
- Mutating the observed element size inside the callback without loop guards, triggering ResizeObserver loop warnings and jank
- Observing hundreds of elements with one observer each instead of one observer with many targets
- Falling back to window resize listeners and missing container-driven size changes in flexible layouts
Related concepts
Related examples
Authoritative source
https://developer.mozilla.org/en-US/docs/Web/API/Resize_Observer_API
What it is
A component often must adapt when its own box changes — flex reflow, sidebar collapse, font loading — not when the window does. Resize Observer reports per-element size changes in a layout-stable moment, removing the need to guess with timers or read geometry in unrelated handlers.
How it works
observe registers a target; on layout changes that alter its boxes, the observer queues a callback for the next frame. The callback receives entries with contentRect and box sizes. Mutations that resize observed elements again fire a subsequent batch, bounded by loop detection that reports a warning instead of spinning forever.
When to use it
Charts, canvases, virtualized tables, embeds, and design-system components that must fit arbitrary hosts. With native container queries handling declarative cases, the observer remains the tool for imperative work like canvas backing-store sizing.
Pitfalls
Read-then-write inside the callback can cascade resize loops across sibling observers; defer writes with rAF when they alter layout. observe fires once initially, which surprises code expecting only subsequent changes. Frame alignment means rapid intermediate sizes coalesce into one notification.