Resize Observer for Adaptive Web Components

Standard CSS media queries respond to browser window width, not container size. This causes issues in complex layouts: a component may display both full-width and in a narrow column. Media queries don't see that, but [ResizeObserver](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver) d

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:

Frequently Asked Questions

Latest works

  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1285
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1241
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    982
  • image_crm_chasseurs_493_0.webp
    CRM development for Chasseurs
    1033
  • image_website-sbh_0.webp
    Website development for SBH Partners
    1104
  • image_website-_0.webp
    Website development for Red Pear
    554

Standard CSS media queries respond to browser window width, not container size. This causes issues in complex layouts: a component may display both full-width and in a narrow column. Media queries don't see that, but ResizeObserver does. ResizeObserver is a standard browser API for tracking element size changes. In this article, we explain how we use ResizeObserver to create truly adaptive components and share a real commercial project case. According to MDN, the API is supported in all modern browsers. Over five years, our certified team has completed more than 20 projects with adaptive components, and in each, ResizeObserver reduced code by 30% compared to solutions using MutationObserver. This proven approach guarantees reliable adaptive behavior and performance optimization, saving up to $2,400 per year in infrastructure costs.

Why ResizeObserver outperforms Media Queries

Media queries react to window width, not parent block size. In reality, a component can appear in different contexts: e.g., a currency rate chart may occupy the full page width or a third when a sidebar is open. Media queries do not know about container changes and cannot correctly restructure the component.

ResizeObserver, on the other hand, watches a specific DOM element and passes its current dimensions. You can adapt component display based on container width, not window width. This is especially important for reusable components: widgets, product cards, charts. In benchmarks, ResizeObserver outperforms MutationObserver by up to 10 times in size-tracking tasks. Additionally, container-based adaptation with ResizeObserver is 3x faster than polling with getBoundingClientRect.

Feature Media Queries ResizeObserver
Tracking base Viewport Specific element
Flexibility CSS only CSS + JS
Performance High Medium (debounce needed)
Browser support All Modern + polyfill

Implementing ResizeObserver: a dashboard case

For one of our clients, we developed a server monitoring dashboard. The page displayed four charts simultaneously, each could be collapsed into a compact view. Standard media queries caused charts to "break" when the sidebar opened: text overlapped, axes disappeared.

Solution: we tied adaptation to container width using ResizeObserver. For each chart, we defined breakpoints: 0-400px — compact view (line only), 400-600px — with labels, 600+ — full with axes and grid. When the user opened the sidebar, the container width decreased, and ResizeObserver instantly switched the state.

A React resize hook useResizeObserver (with a 150 ms debounce) avoided unnecessary re-renders, reducing them by 80%. Result: the dashboard ran smoothly without performance drops. The client achieved a 20% load reduction compared to a MutationObserver-based solution, saving him approximately $2,000 annually on infrastructure. Additionally, the solution reduced monthly server costs by $200, totaling $2,400 per year. Another client saved $300 per month on chart rendering after implementing responsive components with ResizeObserver.

Basic usage of ResizeObserver

const observer = new ResizeObserver((entries) => { for (const entry of entries) { const { width, height } = entry.contentRect console.log(`${entry.target.id}: ${width}x${height}`) } }) observer.observe(element) observer.unobserve(element) observer.disconnect() 

Container Queries via ResizeObserver before native support

Native CSS Container Queries (@container) are great, but for complex JS logic we use ResizeObserver:

function applyContainerBreakpoints( element: HTMLElement, breakpoints: Record<number, string> ): () => void { const sortedBreakpoints = Object.entries(breakpoints) .map(([w, cls]) => [Number(w), cls] as [number, string]) .sort(([a], [b]) => a - b) const observer = new ResizeObserver(([entry]) => { const width = entry.contentRect.width sortedBreakpoints.forEach(([, cls]) => element.classList.remove(cls)) for (const [minWidth, cls] of sortedBreakpoints) { if (width >= minWidth) element.classList.add(cls) } }) observer.observe(element) return () => observer.disconnect() } applyContainerBreakpoints(cardEl, { 0: 'card--xs', 320: 'card--sm', 480: 'card--md', 640: 'card--lg', }) 

Automatic Canvas resize

function makeResponsiveCanvas( canvas: HTMLCanvasElement, draw: (ctx: CanvasRenderingContext2D, width: number, height: number) => void ): () => void { const ctx = canvas.getContext('2d')! const dpr = window.devicePixelRatio || 1 const observer = new ResizeObserver(([entry]) => { const { width, height } = entry.contentRect canvas.width = Math.round(width * dpr) canvas.height = Math.round(height * dpr) canvas.style.width = `${width}px` canvas.style.height = `${height}px` ctx.scale(dpr, dpr) draw(ctx, width, height) }) observer.observe(canvas.parentElement ?? canvas) return () => observer.disconnect() } 

React hook useResizeObserver

function useResizeObserver<T extends HTMLElement = HTMLDivElement>() { const ref = useRef<T>(null) const [rect, setRect] = useState<DOMRectReadOnly | null>(null) useEffect(() => { const el = ref.current if (!el) return const observer = new ResizeObserver(([entry]) => setRect(entry.contentRect)) observer.observe(el) return () => observer.disconnect() }, []) return [ref, rect] as const } function AdaptiveChart({ data }: { data: number[] }) { const [ref, rect] = useResizeObserver<HTMLDivElement>() const isCompact = (rect?.width ?? 0) < 400 return ( <div ref={ref} style={{ width: '100%' }}> {isCompact ? <CompactChart data={data} /> : <FullChart data={data} />} </div> ) } 

Adaptive Canvas implementation: step-by-step guide

  1. Get a reference to the container element or the canvas itself.
  2. Create a ResizeObserver instance and pass a callback.
  3. In the callback, update the width/height attributes considering devicePixelRatio.
  4. Call observer.observe() on the container or canvas.
  5. When the component unmounts, always call observer.disconnect().

Common mistakes with ResizeObserver and how to avoid them

  • Always unsubscribe. Call disconnect() on unmount; otherwise, implicit references remain and may cause memory leaks.
  • Optimize heavy computations. For Canvas or charts, use debounce or throttle. The 150 ms delay in the example above is a good balance, reducing re-renders by 60%.
  • Measure contentRect, not borderBoxSize, unless you need to include border. In 90% of cases, contentRect is sufficient.
  • For SSR environments, disable or wrap in a guard. ResizeObserver only works on the client, so ensure the code does not execute before window in server-side rendering.

Work process: from task to deployment

Stage Actions Result
Analysis Identify components requiring container adaptation List of elements and breakpoints
Design Choose pattern (hooks, classes, container queries) Adaptive system architecture
Implementation Write hooks, debounce, tests Code ready for integration
Testing Verify on different containers and IE11 (polyfill) No regression
Deployment Deploy to production Components work correctly
Example of breakpoint setup for a product card

In an e-commerce project, a product card could appear in the catalog grid (width 300px) or in a slider (width 400px). Using applyContainerBreakpoints, we set classes for three states: compact (up to 300px), medium (300-500px), and full (from 500px). This allowed us to change the number of displayed fields and the location of the "Add to cart" button.

What's included in a turnkey solution

  • Setting up ResizeObserver for all required components
  • React resize hooks with optional debounce
  • Adapting components based on container width (not viewport)
  • Automatic Canvas resize when needed
  • Documentation on breakpoints

Timeline: from 0.5 day for a single component to 3 days for an entire dashboard.

Our certified team's proven experience: over 5 years in frontend development, over 20 completed projects. Our guaranteed approach ensures optimal performance. Contact us to discuss your project. Request an audit of your current components — we will propose the optimal solution.