Created
July 1, 2022 16:51
-
-
Save paulohfev/c2927af9117285ccaa7af5524ea5cdd8 to your computer and use it in GitHub Desktop.
Custom React hook for getting the current screen's dimensions
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 getWindowDimensions = () => { | |
const { innerWidth: width, innerHeight: height } = window; | |
return { width, height }; | |
} | |
const useWindowDimensions = () => { | |
const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions()); | |
useEffect(() => { | |
function handleResize() { | |
setWindowDimensions(getWindowDimensions()); | |
} | |
window.addEventListener('resize', handleResize); | |
return () => window.removeEventListener('resize', handleResize); | |
}, []); | |
return windowDimensions; | |
} | |
export default useWindowDimensions; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment