Created
October 24, 2022 15:05
-
-
Save andresgcarmona/c72487bd94f4eaacf3412605a2941ca2 to your computer and use it in GitHub Desktop.
React hook that returns the 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
unction useWindowSize() { | |
const [windowSize, setWindowSize] = useState({ | |
width: undefined, | |
height: undefined, | |
}); | |
useEffect(() => { | |
// only execute all the code below in client side | |
if (typeof window !== 'undefined') { | |
// Handler to call on window resize | |
function handleResize() { | |
// Set window width/height to state | |
setWindowSize({ | |
width: window.innerWidth, | |
height: window.innerHeight, | |
}); | |
} | |
// Add event listener | |
window.addEventListener("resize", handleResize); | |
// Call handler right away so state gets updated with initial window size | |
handleResize(); | |
// Remove event listener on cleanup | |
return () => window.removeEventListener("resize", handleResize); | |
} | |
}, []); // Empty array ensures that effect is only run on mount | |
return windowSize; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment