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
| Width | Height |
|---|---|
| 0 px | 0 px |
Usage
Import the hook from @abhushanaj/react-hooks and use in required component.
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
-
When Server Side Rendering (SSR) is performed, the initial values for
widthandheightwill benull, and the actual dimensions will be reflected once it reaches the browser. -
The API uses the
window.innerHeightandwindow.innerWidthproperties to get window dimension. Learn more about them from MDN.
API Reference
Return Value
| Parameter | Type | Description | Default |
|---|---|---|---|
| width | number|null | The width of the window. | N/A |
| height | number|null | The height of the window. | N/A |