Beyond window resize
The window resize event only fires when the viewport changes, but elements can change size for many other reasons: content loading, a sidebar collapsing, or flexbox reflowing. The ResizeObserver API watches individual elements directly.
- Create an observer with a callback.
- Call observe on any element to start watching it.
- The callback runs whenever that element box size changes, receiving entries with the new dimensions.
Why it is better
- It reports the precise element, not just the window, enabling container queries style behavior in script.
- It batches changes and runs after layout, avoiding the jank of listening to scroll or resize and re reading layout.
- It avoids infinite loops the browser guards against by deferring observations that would themselves cause resizes.
Read width and height from the content box or border box size on each entry, and disconnect the observer when the component unmounts to avoid leaks.
ResizeObserver gives precise, efficient size feedback per element.
Key idea
ResizeObserver watches individual elements for size changes after layout, replacing fragile window resize and polling approaches.