In JavaScript, window interface provides information about the window where your application is running. innerWidth property stores window width in pixels.

Here’s a React component that displays window width:

export default function App() {
  return (
    <div className="App">
      <h1>{window.innerWidth}</h1>
    </div>
  );
}

Component will display window width when it renders.

But what happens when user resizes the window? window.innerWidth value will not be updated.

To update width on resize, call addEventListener on window interface to start listening for ‘resize’ events.

First argument to the addEventListener method is the type of event (‘resize’). Second argument is the event handler.

componentDidMount = () => {
window.addEventListener("resize", this.handleWindowResize);
};

componentDidMount lifecycle method is a good place to add event listener.

Then call removeEventListener() on window to remove event listener. Use componentWillUnmount lifecycle method.

componentWillUnmount = () => {
window.removeEventListener("resize", this.handleWindowResize);
};

In functional components, you can add event listener via useEffect() hook.

First argument to useEffect() is a callback function. Call addEventListener() on window global variable to add an event listener, just like we did in previous examples.

Second argument to the useEffect() hook should be an empty array. So side effect is executed only when component mounts.

useEffect(() => {
    window.addEventListener("resize", handleResize);
  }, []);

To remove an event listener, return a callback function that removes event listener. Like this:

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

Get window width in React Class Components

In class components, we will use componentDidMount lifecycle method and the addEventListener() method to start listening for resize event when the component mounts.

You need to remove event listener when the component unmounts. Use componentWillUnmount() and call removeEventListener() to stop listening.

Here is a step by step tutorial to get window width in React Class components.

Step 1: Initialize class component

To start, we should define the constructor() for the class component.

In it, we initialize a state object with a width property, and bind the event handler.

export default class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = { width: window.innerWidth };
    this.handleWindowResize = this.handleWindowResize.bind(this);
  }
  render() {
    return <h2>Hello, World!</h2>;
  }
}

When we initialize the state object, we set the default value of width property to window.innerWidth. This will set the initial window width, when the component is first rendered to the screen.

Step 2: Define the handleWindowResize method

Next, we should define the handleWindowResize method. Whenever React notices that the user has resized their window, it will call this function. In it, we need to update the value of width property of the state object. We update it to reflect window width after it is changed.

export default class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = { width: window.innerWidth };
    this.handleWindowResize = this.handleWindowResize.bind(this);
  }
  handleWindowResize = () => {
    this.setState({ width: window.innerWidth });
  };
  render() {
    return <h2>Hello, World!</h2>;
  }
}

Step 3: Listen for ‘resize’ event on mount

In order to correctly update the width property of the state object, we need to know whenever the resize event happens, update the state object to current width of the window. In other words, its width after window was resized.

We can ‘look out for’ resize event by setting the addEventListener() method on global window object.

export default class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = { width: window.innerWidth };
    this.handleWindowResize = this.handleWindowResize.bind(this);
  }
  handleWindowResize = () => {
    this.setState({ width: window.innerWidth });
  };
  componentDidMount = () => {
    window.addEventListener("resize", this.handleWindowResize);
};
  render() {
    return <h2>Hello, World!</h2>;
  }
}

The addEventListener() method takes two arguments:

  1. What event to listen for
  2. Which function to call (in other words, what to do) if that event occurs

Changing window width will fire a resize event, which in turn will execute handleWindowResize(). The event handler gets window width and stores it in the state.

Step 4: Remove event listener

When building React web applications, it’s a good practice to remove manually added event listeners after the component unmounts.

Fortunately, React class components have componentWillUnmount() lifecycle method.

The window object also has the removeEventListener method, which will remove the handler for ‘resize’ event.

export default class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = { width: window.innerWidth };
    this.handleWindowResize = this.handleWindowResize.bind(this);
  }
  handleWindowResize = () => {
    this.setState({ width: window.innerWidth });
  };
  componentDidMount = () => {
    window.addEventListener("resize", this.handleWindowResize);
};
  componentWillUnmount = () => {
    window.removeEventListener("resize", this.handleWindowResize);
};
  render() {
    return <h2>Hello, World!</h2>;
  }
}

Final Code

Getting window width in React is as simple as following these three steps.

Here is a full component code and live demo on CodeSandbox.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { width: window.innerWidth };
    this.handleWindowResize = this.handleWindowResize.bind(this);
  }
  handleWindowResize = () => {
    this.setState({ width: window.innerWidth });
  };
  componentDidMount = () => {
    window.addEventListener("resize", this.handleWindowResize);
  };
  componentWillUnmount = () => {
    window.removeEventListener("resize", this.handleWindowResize);
  };
  render() {
    return (
      <div style={{ textAlign: "center" }}>
        <h1>Current window width:</h1>
        <h1>{this.state.width}</h1>
      </div>
    );
  }
}

Get window width in React Functional Components

Next, let’s explore how to do this in functional components.

In this section, we will break down how to create a custom hook that gets current window width and returns it. Custom hooks allow React web developers to implement a specific functionality and reuse it, without having to write the code all over again. You can think of them as more advanced helper functions.

Once we define the custom hook, we can ‘borrow’ it to get window width in many different components.

Step 1: Set up a custom hook to get window with

Creating a custom hook might sound scary, but it’s easier than you may think.

We simply have to define a function accesses innerWidth property of the window object, and stores it in the state. The hook itself should return the state variable.

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);
    return () => window.removeEventListener("resize", handleResize);
  }, []);
  return width;
}

To implement this functionality, we need useState() and useEffect() hooks.

First we initialize width state variable and setWidth, the function to update it.

As you may know, the argument to the useState() hook will be the initial value of width state variable. In this case, we set it to window.innerWidth – the width when the component is first rendered.

Step 2: Add event listener and define event handler

We use the useEffect() hook to call addEventListener() on the window object. This way, React will start listening for resize events after the component is mounted.

The addEventListener() function takes two arguments. One specifies what event to listen for (in this case, 'resize' ). Second one specifies which function to call when this event occurs (in this case, handleResize).

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);
  function handleResize() {
      setWidth(window.innerWidth);
    }
  useEffect(() => {
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []); 
  return width;
}

We also define the handleResize() function, which will be executed every time a resize event occurs.

The resize event changes width of the window. That’s why handleResize() function calls the setWidth function to update the state variable to current window width.

Finally, the custom hook returns state variable width.

Step 3: Using custom hook to get window width in React

In previous step, we defined the useWindowWidth() custom hook.

Sometimes you need to import the custom hook from external file. In this case, we defined it in the same file as main component, so we can just call the useWindowWidth() hook.

You can simply create a variable and set its value to instance of the useWindowWidth() hook. Let’s look at an example:

export default function App() {
  const width = useWindowWidth();
  return (
    <div className="App">
      <h1>{width}</h1>
    </div>
  );
}

Get Window Width on Resize in React

React allows you to access window width (in pixels) every time the window is resized. Just make sure to add an event listener for resize event, and create an event handler that gets current width of the resized window.

The beauty of React is that you can get window width every time window is resized. The trick is to add an event listener for resize event, and create an event handler that gets width of the resized window.

You need to use componentDidMount() lifecycle method or useEffect() effect hook to add the event listener by calling addEventListener() on the window object.

addEventListener() takes two arguments – the event to look out for ('resize') and the function to call when the event occurs.

Event handler should access the current width and stores it in the state.

For example, look at the custom hook we defined before:

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);
  function handleResize() {
      setWidth(window.innerWidth);
    }
  useEffect(() => {
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);
  return width;
}

You can use this hook to get window width on resize in React. Our article also contains code examples to get window width on resize in class components.

Get Current Window Width in React

As we mentioned before, whenever you access innerWidth property of the window object, it will return current width of the window.

To get current window width in React, you should add an event listener for a resize event. Whenever this event occurs, call a function that saves the updated window.innerWidth value in the state.

Our examples above explain how to do this in detail.

Simply use the addEventListener() method to listen for resize events. This method takes two arguments – what event to look out for, and the event handler to call when that event happens. The event handler will get current window width in React and store it in the state.

It’s best to add event listeners in the componentDidMount() lifecycle hook, or in the callback function of useEffect() hook.