useWindowSizeLoading saved progress…

useWindowSize

Build a custom React hook that tracks the size of the browser window. Reading window.innerWidth once gives you a number that's correct now and wrong the instant the user resizes, rotates their phone, or opens devtools. useWindowSize() returns a live { width, height } that re-renders the component every time the window's dimensions change — the building block for responsive layouts, conditional rendering by breakpoint, and canvas sizing.

Signature

function useWindowSize(): {
  width: number;
  height: number;
};

The hook takes no arguments and returns the current window dimensions. The returned object must update — triggering a re-render — whenever the window resizes.

Examples

function Layout() {
  const { width, height } = useWindowSize();

  return (
    <div>
      {width}×{height}
      {width < 768 ? <MobileNav /> : <DesktopNav />}
    </div>
  );
}
// On a 1024×768 window: shows "1024×768" and DesktopNav.
// Drag the window down to 700px wide: re-renders to "700×768" and MobileNav.
// The values are plain numbers read from the window:
const { width, height } = useWindowSize();
// width === window.innerWidth, height === window.innerHeight, kept in sync.

Notes

  • Update on resize. The returned size must reflect the current window after a resize, not just the size at mount. A hook that only reads once is the common mistake.
  • Clean up the listener. Remove the resize listener when the component unmounts, or it leaks and keeps calling a setter on a component that's gone.
  • Both dimensions. Track width and height together; many layouts depend on height (viewport-fitting panels) as much as width.
  • No SSR handling required. Assume window exists. Server-side rendering guards are out of scope here.
Loading editor…