Last active
April 8, 2020 17:42
-
-
Save camilomontoyau/89410a22ae4e0b980ddd389da6f5bd48 to your computer and use it in GitHub Desktop.
react hook for listening window resize event
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
function useWindowSize() { | |
const isClient = typeof window === 'object'; | |
function getSize() { | |
return { | |
width: isClient ? window.innerWidth : undefined, | |
height: isClient ? window.innerHeight : undefined | |
}; | |
} | |
const [windowSize, setWindowSize] = useState(getSize); | |
useEffect(() => { | |
if (!isClient) { | |
return false; | |
} | |
function handleResize() { | |
setWindowSize(getSize()); | |
} | |
window.addEventListener('resize', handleResize); | |
return () => window.removeEventListener('resize', handleResize); | |
}, []); // Empty array ensures that effect is only run on mount and unmount | |
return windowSize; | |
} | |
export useWindowSize; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment