Technology that earns its place.

Using ResizeObserver when an element changes size

A developer testing a responsive card layout on a laptop and wide monitor at a modest desk.
AI-generated photographic illustration; not documentary photography.

A chart becomes narrower when a sidebar opens, even though the browser window stays the same width. Code that listens only for the window’s resize event may miss that change. The component’s available space has changed inside the layout.

ResizeObserver provides notifications about changes to an observed element’s size. It is useful when JavaScript needs to react to the space a component actually receives, rather than infer that space from the viewport.

Observe the element whose space matters

This small diagnostic example assumes the page contains an element with the class chart-panel. It logs the content rectangle rather than changing the layout:

const panel = document.querySelector('.chart-panel');
const observer = new ResizeObserver(entries => {
  for (const entry of entries) {
    console.log(entry.contentRect.width, entry.contentRect.height);
  }
});
if (panel) observer.observe(panel);
// Call observer.disconnect() when this component is removed.

Open and close the surrounding sidebar while watching the console. The useful test is whether the panel measurement changes even when the viewport does not. For production rendering, choose the appropriate observed box and measurement for the component, and handle its lifecycle explicitly.

Avoid measuring yourself into a loop

If the callback repeatedly increases the observed element’s width, that change can trigger another notification. MDN describes how the browser handles undelivered resize notifications, but its protection does not repair the application’s underlying feedback loop. Deferring work to another animation frame alone does not make an endlessly changing layout correct.

Keep the reaction bounded. Compare the desired state with the current state, avoid unnecessary writes and make sure the update can settle. A chart renderer might need a new drawing size without altering the container that determined it.

Before adding JavaScript, ask whether ordinary CSS layout or a container query can solve the visual requirement. Reserve observation for work that actually needs a programmatic response, such as redrawing a canvas. Then test nested layouts, hidden-to-visible transitions and component removal. The observer follows an element, but the application still owns the consequences of responding to it.