How to use the Resize Observer API

· Category: JavaScript & Web

Short answer

The Resize Observer API watches for changes to the content box or border box of DOM elements and fires a callback with the new dimensions, avoiding expensive window.resize polling.

Details

Basic usage targets a single element:

const observer = new ResizeObserver((entries) => {
  for (const entry of entries) {
    console.log(entry.contentRect.width, entry.contentRect.height);
  }
});
observer.observe(document.getElementById('chart'));

This is ideal for canvas rendering, responsive typography, and custom layout engines. Because it runs outside the main animation frame, it helps protect Core Web Vitals by reducing layout thrashing. If you need to transform observed sizes into derived UI states, combine the callback with array map/filter/reduce over your component registry. Disconnect the observer when components unmount to prevent memory leaks.

Tips

  • Observe the smallest container possible rather than the entire document.
  • Use entry.borderBoxSize for precise sizing when padding and borders matter.
  • Debounce heavy layout recalculations inside the callback if they trigger repaints.