← Lessons

quiz vs the machine

Platinum1740

Frontend

The Resize Observer

React to an element changing size without polling or window resize hacks.

5 min read · advanced · beat Platinum to climb

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.

Check yourself

Answer to earn rating on the learn ladder.

1. What does ResizeObserver watch?

2. Why is ResizeObserver preferred over listening to window resize?

3. What should you do when the component using a ResizeObserver unmounts?