To listen for browser window resize events in JavaScript, attach an event listener to window using window.addEventListener("resize", handler) (and remove it later with window.removeEventListener("resize", handler) when cleaning up components or listeners). Because resize fires repeatedly during active dragging or orientation changes, wrapping the handler in requestAnimationFrame() or a debounce/throttle helper prevents layout thrashing and excessive work on every pixel change.


1. Basic Window Resize Listener and Cleanup

Register a named handler with window.addEventListener("resize", onResize) and pass the exact same function reference to window.removeEventListener("resize", onResize) when you no longer need it:

// Read current viewport dimensions and clean up the listener when done
function handleWindowResize() {
  const width = window.innerWidth;
  const height = window.innerHeight;
  console.log(`Viewport size: ${width}x${height}`);
}

window.addEventListener("resize", handleWindowResize);

// Later, when tearing down or cleaning up:
// window.removeEventListener("resize", handleWindowResize);
  • Keep a named function reference: Passing an inline arrow function to addEventListener makes removeEventListener impossible later.
  • Avoid reading layout properties blindly on every event: Querying getBoundingClientRect() repeatedly inside a raw resize listener can force synchronous reflows.

2. Coalescing Resize Work with requestAnimationFrame

Resizing a browser window can trigger dozens of resize events per second; coalescing DOM or canvas updates with requestAnimationFrame() runs your measurement once per display frame:

// Throttle resize handling to at most once per animation frame
function observeViewportResize(onSizeChange) {
  if (typeof onSizeChange !== "function") {
    throw new TypeError("Expected onSizeChange to be a function.");
  }

  let frameId = null;

  const scheduleUpdate = () => {
    if (frameId !== null) return;

    frameId = window.requestAnimationFrame(() => {
      frameId = null;
      onSizeChange({
        width: window.innerWidth,
        height: window.innerHeight
      });
    });
  };

  // Trigger once immediately so initial dimensions match
  scheduleUpdate();
  window.addEventListener("resize", scheduleUpdate, { passive: true });

  return () => {
    window.removeEventListener("resize", scheduleUpdate);
    if (frameId !== null) {
      window.cancelAnimationFrame(frameId);
    }
  };
}

// Example usage:
const stopObserving = observeViewportResize(({ width, height }) => {
  console.log("Updated size:", width, height);
});
  • Run an initial check: The resize event does not fire on initial page load, so calling your handler once upfront syncs state immediately.
  • Use { passive: true } and cancel pending frames: Clean teardown prevents memory leaks and callbacks running after cleanup.

3. Window resize vs. ResizeObserver for Specific Elements

Use window.addEventListener("resize", ...) when your logic depends on the browser viewport (such as mobile vs. desktop breakpoints), and use ResizeObserver when watching a specific DOM element whose size changes from layout shifts, fonts, or sidebars without resizing the window:

// Watch a specific container element's box size instead of the full window
function observeElementSize(element, onBoxChange) {
  if (!(element instanceof Element)) {
    throw new TypeError("Expected a valid DOM Element.");
  }

  const observer = new ResizeObserver((entries) => {
    for (const entry of entries) {
      const { width, height } = entry.contentRect;
      onBoxChange({ width, height });
    }
  });

  observer.observe(element);
  return () => observer.disconnect();
}
  • Pick the right scope: ResizeObserver fires initially upon .observe() and tracks individual element boxes accurately.
  • Use window.matchMedia() for CSS breakpoints: When reacting only to media-query crossings, a MediaQueryList "change" listener is often cleaner than polling window.innerWidth on every resize.