Sometimes we need web applications to respond to window size changes. In this article, we will show how to access window width in React, and implement responsivity features for best UX possible.

Specific Examples
Get window width in React
React is one of three main JavaScript-based libraries. All React code is ultimately ‘translated’ to JavaScript, even the parts that look like HTML.
When writing JavaScript code, we can access window properties via the window
global variable, which refers to the window where your application is running.
To get the width of window in React, we need to access the innerWidth
property of window
global variable. Accessing the width is not the difficult part. The bigger question is, how to use window width value within React to make your web application more interactive and improve its UX.
We will address these concerns in sections below.
Get window width in React Class Components
For class components, we will use lifecycle method and the addEventListener()
method to listen for resize
event on the window
object. Every time the resize
event occurs, event listener will call a function that accesses window.innerWidth
value and saves it in the state.
We need to add event listener to the window
object when it’s first mounted. Once added, the function will run every time it notices a window resize
event. To be clear, lifecycle method is used to define when we add the event listener, not when the function should run.
Finally, we also need to remove the event listener once the component unmounts. For that, we’ll use componentWillUnmount()
lifecycle method.
Let’s go over each step of how 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 initializing 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:
- What event to listen for
- 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);
useEffect(() => {
window.addEventListener("resize", handleResize);
function handleResize() {
setWidth(window.innerWidth);
}
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.