Learn how to make your layouts adaptive, efficient, and event-free with the Resize Observer API.

Introduction
Have you ever written a layout that looked perfect until someone resized the browser window? Suddenly, your grid breaks, your sidebar overflows, and your “responsive” design isn’t so responsive anymore.
Most developers reach for the window. resize events to handle such situations, but that approach quickly gets messy. Multiple listeners, performance issues, and unnecessary recalculations become the norm.
That’s where the Resize Observer API comes in. It’s a modern browser feature that lets you watch element size changes directly, not the entire window, giving you precise control over dynamic layouts, charts, or any responsive component.
In this post, you’ll learn:
- What Resize Observer is and why it’s better than
window.resize - How to use it with real-world JavaScript and React examples
- How to handle performance, cleanup, and nested element updates
- Advanced tips and gotchas you should know before using it in production
Let’s dive in.
1. What Is Resize Observer?
The Resize Observer API allows you to observe when an element’s content rectangle changes, in simple terms, when its width or height changes.
Unlike window.onresize, which fires on every browser resize. Resize Observer listens for changes to specific elements, giving you fine-grained control.
Quick Example
const box = document.querySelector('.box');
const observer = new ResizeObserver(entries => {
for (let entry of entries) {
console.log('New size:', entry.contentRect.width, entry.contentRect.height);
}
});
observer.observe(box);
This snippet logs the new width and height every time the .box element changes its size due to CSS changes, user actions, or JavaScript updates.
2. Why Not Just Use window.resize?
Developers have been using it window.addEventListener('resize', ...) for years. It works, but it’s not ideal.
Here’s why Resize Observer is smarter:

Think of window.resize as a global event, like shouting in a crowded room while ResizeObserver It’s like getting a personal notification when a specific element changes.
3. How to Use Resize Observer (Step-by-Step)
Let’s see how you’d actually use it in your project.
Step 1: Create and Attach an Observer
const observer = new ResizeObserver(entries => {
entries.forEach(entry => {
const { width, height } = entry.contentRect;
console.log(`Element resized: ${width}x${height}`);
});
});
observer.observe(document.querySelector('#target'));
Step 2: Stop Observing When Done
Always disconnect when you no longer need it, especially in single-page apps like React.
observer.unobserve(document.querySelector('#target'));
observer.disconnect(); // removes all observations
Step 3: Handle Multiple Elements
You can observe multiple elements easily.
const elements = document.querySelectorAll('.track');
elements.forEach(el => observer.observe(el));
4. Using Resize Observer in React
Let’s bring this into a React component.
Here’s a simple example that tracks the width of a container:
import { useEffect, useRef, useState } from "react";
function ResponsiveBox() {
const ref = useRef(null);
const [size, setSize] = useState({ width: 0, height: 0 });
useEffect(() => {
const element = ref.current;
if (!element) return;
const observer = new ResizeObserver(entries => {
const { width, height } = entries[0].contentRect;
setSize({ width, height });
});
observer.observe(element);
return () => observer.disconnect();
}, []);
return (
<div
ref={ref}
style={{
resize: "both",
overflow: "auto",
padding: "1rem",
border: "1px solid #ccc"
}}
>
<p>Width: {size.width.toFixed(0)}px</p>
<p>Height: {size.height.toFixed(0)}px</p>
</div>
);
}
export default ResponsiveBox;
Now try resizing the element, it live-updates its own dimensions.
This approach is excellent for dashboards, charts, or split-view editors where components need to react to their container’s size.
5. Real-World Use Cases
Here are some situations where Resize Observer shines:
1. Responsive Charts
Chart libraries like D3 or Chart.js can re-render intelligently when their container changes size.
2. Adaptive Grids or Cards
Recalculate grid item counts when the parent container width changes.
3. Dynamic Sidebars
When sidebars expand/collapse, content areas can auto-adjust.
4. Text Areas That Auto-Grow
ResizeObserver can track auto-resizing text inputs.
5. Split-View Editors
When users drag a divider, the editor panes can re-render in sync.
6. Performance Tips and Gotchas
Even though Resize Observer is efficient, there are a few things to watch out for.
1. Avoid Infinite Loops
If your resize callback changes the element’s size again, you can trigger recursive updates.
Solution: Use conditions to detect actual value changes before re-rendering.
2. Debounce for Heavy Updates
If resizing triggers expensive operations (like chart re-renders), debounce them manually.
let timeout;
const observer = new ResizeObserver(entries => {
clearTimeout(timeout);
timeout = setTimeout(() => {
// Your heavy logic here
}, 150);
});
3. Use contentBoxSize for Precision
Modern browsers provide detailed size info for complex layouts.
const observer = new ResizeObserver(entries => {
const { inlineSize, blockSize } = entries[0].contentBoxSize[0];
console.log(inlineSize, blockSize);
});
7. Browser Support and Polyfills
Resize Observer is widely supported in modern browsers.
✅ Chrome, Edge, Safari, and Firefox all support it.
❌ Internet Explorer doesn’t (but who’s building for that anymore?).
If you need backward compatibility, use the resize-observer-polyfill package:
npm install resize-observer-polyfill
Then:
import ResizeObserver from 'resize-observer-polyfill';
This ensures consistent behavior across older environments.
8. Comparison Recap: window.resize vs ResizeObserver

If your app is built around modular, reusable components, Resize Observer is the right choice.
9. Advanced Pattern: Combining with Mutation Observer
Sometimes element resizing is triggered by DOM mutations (like toggling visibility). Combine both observers to handle layout shifts + structure changes together.
const resizeObserver = new ResizeObserver(handleResize);
const mutationObserver = new MutationObserver(handleMutation);
resizeObserver.observe(target);
mutationObserver.observe(target, { attributes: true, childList: true });
This combo makes your UI reactive to structure and size, perfect for dynamic dashboards or CMS editors.
Conclusion
The Resize Observer API is one of those small but powerful tools that make your frontend code cleaner and smarter. Instead of relying on clunky window.resize Listeners, you can now observe element-level changes directly, leading to more maintainable and efficient UIs.
Whether you’re building a charting dashboard, a resizable editor, or a grid-based layout, Resize Observer helps your app respond precisely to what users do, not just to browser events.
Pro Tip: Combine ResizeObserver with requestAnimationFrame or throttling when handling animations or large DOM updates for optimal performance.
Call to Action
Have you used Resize Observer in a real project?
Share your experience in the comments, and if this helped you, bookmark it for your next responsive UI build.


Leave a Reply