Read the browser viewport's width and height (in CSS pixels), staying
in sync as the window is resized.
Backed by useSyncExternalStore, so it is safe under concurrent rendering
and does not tear. width and height are undefined on the server —
and on the client until the first resize-store read commits — the same
"unknown until proven otherwise" contract useTheme uses for theme,
applied to both fields here since neither has a safe default to guess.
width and height in CSS pixels, each undefined until the
client has reported the real viewport size. The returned object is
memoized, so its identity only changes when a dimension does.
Example
const { width, height } = useWindowSize(); if (width === undefined || height === undefined) returnnull; // avoid laying out against an unknown size return<div>{width} × {height}</div>;
Read the browser viewport's
widthandheight(in CSS pixels), staying in sync as the window is resized.Backed by
useSyncExternalStore, so it is safe under concurrent rendering and does not tear.widthandheightareundefinedon the server — and on the client until the first resize-store read commits — the same "unknown until proven otherwise" contractuseThemeuses fortheme, applied to both fields here since neither has a safe default to guess.