Course contentsShow
← React
Lesson 739 of 2,39619. useRefFree lesson

Responsive Layouts with ResizeObserver

Attach a ResizeObserver to a ref in useEffect to track element size changes and update state.

Responsive Layouts with ResizeObserver

You'll learn how to track element size changes in real-time using ResizeObserver and refs, enabling dynamic layouts that respond to container size rather than just viewport width.

The Core Idea

Sometimes you need to know when an element's size changes — not just the window, but a specific element within your layout. Maybe a sidebar collapses, or a parent container resizes, and you need to adjust child components accordingly. The ResizeObserver API watches an element and fires a callback whenever its dimensions change.

You attach this observer to a DOM node using a ref inside useEffect, and update state with the new dimensions.

The Pattern

function ResponsiveCard() {
  const [width, setWidth] = useState(0);
  const cardRef = useRef(null);

  useEffect(() => {
    const element = cardRef.current;
    if (!element) return;

    const observer = new ResizeObserver((entries) => {
      const entry = entries[0];
      setWidth(entry.contentRect.width);
    });

    observer.observe(element);

    return () => observer.disconnect();
  }, []);

  return (
    <div ref={cardRef}>
      <p>Card width: {Math.round(width)}px</p>
      {width < 300 ? <CompactView /> : <ExpandedView />}
    </div>
  );
}

The observer fires whenever the element resizes, updating your state. You can then conditionally render different layouts based on the actual container size, not just media queries.

Think of It Like...

A motion sensor that watches one specific door. Instead of monitoring the whole building (window resize), you're tracking whether this particular element has changed dimensions.

Key Takeaway: Attach a ResizeObserver to a ref in useEffect to track element-specific size changes and update state, enabling container-query-like behavior in React.