Skip to content

useWindowSize

Get and track the dimensions of the window from your component.

The useWindowSize hook is helpful when you want retrieve and track the dimensions of the current window. It is useful for layout adjusments and conditional rendering of any component based on window size.

It uses the window.innerWidth and window.innerHeight properties and also setup a subscription to the resize event to get latest values at all times. When using SSR, it will result in null values for width and height.

useWindowSize

WidthHeight
0 px0 px
Resize your screen to see changes in window dimenions.

Usage

Import the hook from @abhushanaj/react-hooks and use in required component.

./src/App.tsx
import { useWindowSize } from '@abhushanaj/react-hooks';
function App() {
const { width, height } = useWindowSize();
return (
<div>
<p>Window Width is : {width ?? 0} px</p>
<p>Window Height is : {height ?? 0} px</p>
</div>
);
}
export default App;

Properties

  1. When Server Side Rendering (SSR) is performed, the initial values for width and height will be null, and the actual dimensions will be reflected once it reaches the browser.

  2. The API uses the window.innerHeight and window.innerWidth properties to get window dimension. Learn more about them from MDN.

API Reference

Return Value

ParameterTypeDescriptionDefault
widthnumber|nullThe width of the window.N/A
heightnumber|nullThe height of the window.N/A