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.
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.
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.
resize listener when the component unmounts, or it leaks and keeps calling a setter on a component that's gone.width and height together; many layouts depend on height (viewport-fitting panels) as much as width.window exists. Server-side rendering guards are out of scope here.