Get window Width and Height in React

avatar

Borislav Hadzhiev

Wed Apr 27 20222 min read

banner

Photo by Samuel Ng

Get window Width and Height in React #

To get the width and height of the window in React:

  1. Use the innerWidth and innerHeight properties on the window object.
  2. Add an event listener for the resize event in the useEffect hook.
  3. Keep changes to the width and height of the window in a state variable.
App.js
import {useEffect, useState} from 'react'; export default function App() { const [windowSize, setWindowSize] = useState(getWindowSize()); useEffect(() => { function handleWindowResize() { setWindowSize(getWindowSize()); } window.addEventListener('resize', handleWindowResize); return () => { window.removeEventListener('resize', handleWindowResize); }; }, []); return ( <div> <h2>Width: {windowSize.innerWidth}</h2> <h2>Height: {windowSize.innerHeight}</h2> </div> ); } function getWindowSize() { const {innerWidth, innerHeight} = window; return {innerWidth, innerHeight}; }

react get window width

We initialized a state variable called windowSize that tracks changes to the width and height of the window object.

The innerWidth property returns the interior width of the window in pixels. This includes the width of the vertical scroll bar (if one is present).

The innerHeight property returns the interior height of the window in pixels, including the height of the horizontal scroll bar (if present).

We passed an empty dependencies array to the useEffect hook because we only want to add an event listener for the resize event once - on the initial render.

App.s
useEffect(() => { function handleWindowResize() { setWindowSize(getWindowSize()); } window.addEventListener('resize', handleWindowResize); return () => { window.removeEventListener('resize', handleWindowResize); }; }, []);

The resize event is fired when the window has been resized.

Every time the window is resized, we update the windowSize state variable according to the new innerWidth and innerHeight of the window.

The function we returned from the useEffect hook will get invoked when the component unmounts.

We used the removeEventListener method to remove the event listener that we previously registered.

The cleanup step is important, because we want to make sure we don't have any memory leaks in our application.

Use the search field on my Home Page to filter through my more than 1,000 articles.