Sometimes it's necessary to execute logic in a React app when the browser is resized or when the mobile device is rotated. This is done by handling the resize event in JavaScript. The React render lifecycle runs whenever the page content changes, usually in response to input. To install a handler, it's necessary for the code to run once, certainly not in the render loop.

Modern React apps use hooks, so calling a method once is a little tricky. Calling useEffect without any dependencies accomplishes this feat.

The code below shows the simplest method to do this.

import { useEffect, useState } from 'react';
import './App.css';

function resize(setWidth) {
  setWidth(window.innerWidth);
}

function App() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    window.addEventListener('resize', () => resize(setWidth));
    return () => {
      window.removeEventListener('resize', () => resize(setWidth));
    };
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        <div>
          Height: {window.innerHeight} Width: {width}
        </div>
      </header>
    </div>
  );
}

export default App;

You might notice something odd about this code. There is only a hook to set the width, however window.innerHeight also updates when the window is resized. This occurs because the resize event triggers a render, during which React updates the display, including the current value of window.innerHeight.