Created
July 14, 2020 01:49
-
-
Save sirdarthvader/5bb8098ae30a5983578c3b44397eef4f to your computer and use it in GitHub Desktop.
React Hook function for calculating viewport dimension.
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 {useState, useEffect} from 'react'; | |
const useViewport = () => { | |
const [width, setWidth] = useState(window.innerWidth); | |
const [height, setHeight] = useState(window.innerHeight); | |
useEffect(() => { | |
const handleWindowResize = () => { | |
setWidth(window.innerWidth); | |
setHeight(window.innerHeight); | |
}; | |
window.addEventListener('resize', handleWindowResize); | |
return () => window.removeEventListener('resize', handleWindowResize); | |
}, []); | |
// Return the width and height so we can use it in our components | |
return {width, height}; | |
}; | |
export default useViewport; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment