useWindowSize
React Element Hooks that tracks window size
useWindowSize reactively tracks the browser window’s innerWidth and innerHeight. It returns an object with width and height properties that update automatically whenever the window is resized. This is useful for any component logic that depends on viewport dimensions.
When to Use
- Building responsive layouts that need to adapt logic (not just CSS) based on viewport size
- Dynamically calculating how many items to render in a grid or virtual list
- Adjusting canvas, chart, or map dimensions to fill the available viewport
Notes
- SSR-safe: Returns
{ width: 0, height: 0 }during server-side rendering sincewindowis not available. - Performance: Listens to the window
resizeevent. The observer is cleaned up automatically on unmount. - See also
useElementSizefor tracking the size of a specific element, anduseElementBoundingfor full bounding-box data including position.
Usage
Live Editor
function Demo() { const { width, height } = useWindowSize(); return ( <div> <p> width: {width}, height: {height} </p> </div> ); };
Result
API
useWindowSize
Returns
{ readonly width: number; readonly height: number; }: A object with the following elements:
- width: The current window width.
- height: The current window height.