Created
June 21, 2021 20:59
-
-
Save mahdiyazdani/402b871fb9f55f72e47d9b633ee5935c to your computer and use it in GitHub Desktop.
useWindowDimensions React Hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
function useWindowDimensions() { | |
const [width, setWidth] = React.useState(window.innerWidth); | |
const [height, setHeight] = React.useState(window.innerHeight); | |
React.useEffect(() => { | |
const handleResize = () => { | |
setWidth(window.innerWidth); | |
setHeight(window.innerHeight); | |
}; | |
const resize = window.addEventListener('resize', handleResize); | |
return () => window.removeEventListener(resize, handleResize); | |
}); | |
return { | |
width, | |
height, | |
}; | |
} | |
function App() { | |
const { width, height } = useWindowDimensions(); | |
return ( | |
<div className="App"> | |
<h2>width: {width}</h2> | |
<h2>height: {height}</h2> | |
<p>Resize the window.</p> | |
</div> | |
); | |
} | |
const rootElement = document.getElementById('root'); | |
ReactDOM.render(<App />, rootElement); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment