JS ResizeObserver Pattern for Adaptive Layout
Before CSS Container Queries, adapting a component to its parent required observing box dimensions with ResizeObserver in JavaScript and toggling conditional classes after the initial render.
Adaptive Layout: ResizeObserver vs @container
useEffect(() => {
const ro = new ResizeObserver(([e]) => {
setCompact(e.contentRect.width < 400);
});
ro.observe(ref.current);
return () => ro.disconnect();
}, []);Causes a visual layout flash after hydration.
.card-wrap { container-type: inline-size; }
@container (min-width: 400px) {
.card { grid-template-columns: 1fr 1fr; }
}Evaluated on the first Paint without hydration.
Under the Hood
- The engine executes the initial Layout pass of the Browser Rendering Pipeline using default classes.
ResizeObserverinvokes the JS callback right before Paint with the measuredcontentRect.- Mutating component state (
setState/classList.toggle) invalidates style and forces a second Layout calculation on the next frame.
// Legacy pattern: measures box after Layout, then dirties Layout again
const ro = new ResizeObserver(([entry]) => {
const isWide = entry.contentRect.width >= 420;
card.classList.toggle('card--wide', isWide);
});
ro.observe(cardSlot);Problem Genealogy
- 2015 (Element Queries polyfills): Expensive
window.resizelisteners blind to CSS-driven layout changes. - 2019 (
ResizeObserver+ React Hooks): Asynchronous box observation, but delayed by one frame relative to SSR, guaranteeing a visible layout snap on hydration. - 2023+ (
@container): Native single-pass Layout resolution with zero JS.
Production Pitfalls
ResizeObserver loop completed with undelivered notifications: Resizing a parent inside a child's observer callback creates multi-frame oscillation that browsers eventually abort with a console warning.- Hydration visual flash (CLS): During SSR, container width is unknown; the component snaps abruptly after client mount.
- When not to use
ResizeObserver: Stop using it for responsive CSS styling; reserve it for<canvas>or WebGL viewport resizing.
Connections & Logical Next Steps
Floating engines observe reference and floating element resizes to keep coordinates accurate.
Variable-height virtualized rows rely on ResizeObserver to measure and cache actual row heights.
ResizeObserver callbacks execute between Layout and Paint, triggering a second style recalculation cycle.
ResizeObserver mutates styles in JS after Layout, whereas @container queries resolve size rules in one CSS pass.
Eliminates ResizeObserver + JS class toggling to adapt components to their container.