CSS & LayoutSuperseded

JS ResizeObserver Pattern for Adaptive Layout

Mental Model

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.

Interactive Simulator

Adaptive Layout: ResizeObserver vs @container

Lines of Code
Before
7
After
4
Reflows / Browser Cost
Before
2 passes (SSR -> client)
After
1 native pass
BeforeJS ResizeObserver + State Hack
useEffect(() => {
  const ro = new ResizeObserver(([e]) => {
    setCompact(e.contentRect.width < 400);
  });
  ro.observe(ref.current);
  return () => ro.disconnect();
}, []);
Lines: 7Reflows: 2 passes (SSR -> client)Dependencies: React Hook + Observer

Causes a visual layout flash after hydration.

After (Native)Native CSS @container
.card-wrap { container-type: inline-size; }
@container (min-width: 400px) {
  .card { grid-template-columns: 1fr 1fr; }
}
Lines: 4Reflows: 1 native passDependencies: 0 JS

Evaluated on the first Paint without hydration.

Live Container:Layout: 2 columns (grid)

Under the Hood

  1. The engine executes the initial Layout pass of the Browser Rendering Pipeline using default classes.
  2. ResizeObserver invokes the JS callback right before Paint with the measured contentRect.
  3. Mutating component state (setState / classList.toggle) invalidates style and forces a second Layout calculation on the next frame.
JS
// 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.resize listeners 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

Production Pitfall
  • 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
  • When not to use ResizeObserver: Stop using it for responsive CSS styling; reserve it for <canvas> or WebGL viewport resizing.

Connections & Logical Next Steps

Mechanical Comparisons