You can use the
hook to manage the width and height state variables, and theuseState
hook to add and remove theuseEffect
event listener. Theresize
dependency array passed to useEffect ensures that the effect only runs once (on mount) and not on every re-render.[]
import React, { useState, useEffect } from "react";function WindowDimensions() {const [dimensions, setDimensions] = useState({width: window.innerWidth,height: window.innerHeight,});useEffect(() => {function handleResize() {setDimensions({width: window.innerWidth,height: window.innerHeight,});}window.addEventListener("resize", handleResize);return () => window.removeEventListener("resize", handleResize);}, []);return (<span>{dimensions.width} x {dimensions.height}</span>);}
Using Class Component
You can listen to the
event inresize
and then update the dimensions (componentDidMount()
andwidth
). You should remove the listener inheight
method.componentWillUnmount()
class WindowDimensions extends React.Component {constructor(props) {super(props);this.updateDimensions = this.updateDimensions.bind(this);}componentWillMount() {this.updateDimensions();}componentDidMount() {window.addEventListener("resize", this.updateDimensions);}componentWillUnmount() {window.removeEventListener("resize", this.updateDimensions);}updateDimensions() {this.setState({width: window.innerWidth,height: window.innerHeight,});}render() {return (<span>{this.state.width} x {this.state.height}</span>);}}