Created
March 15, 2021 11:34
-
-
Save gh640/131e7017e2bdd2c918d312e87aa23f71 to your computer and use it in GitHub Desktop.
React hook to get the reactive window size
This file contains hidden or 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' | |
| function useWindowSize() { | |
| const [windowSize, setWindowSize] = useState({ | |
| width: null, | |
| height: null, | |
| }) | |
| useEffect(() => { | |
| const updateSize = () => { | |
| setWindowSize({ | |
| width: window.innerWidth, | |
| height: window.innerHeight, | |
| }) | |
| } | |
| window.addEventListener("resize", updateSize) | |
| updateSize() | |
| return () => window.removeEventListener("resize", updateSize) | |
| }, []) | |
| return windowSize | |
| } | |
| export default useWindowSize |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment