Created
April 30, 2021 14:24
-
-
Save erictherobot/c8e14442b13198d36b9cbab8481b6c92 to your computer and use it in GitHub Desktop.
Screen Width & Height Hook
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'; | |
export function useScreen() { | |
const getScreen = () => { | |
if (typeof window !== 'undefined') { | |
return window.screen; | |
} | |
return undefined; | |
}; | |
const [screen, setScreen] = useState<Screen | undefined>(getScreen()); | |
useEffect(() => { | |
function handleResize() { | |
setScreen(getScreen()); | |
} | |
window.addEventListener('resize', handleResize); | |
return () => { | |
window.removeEventListener('resize', handleResize); | |
}; | |
// Empty array ensures that effect is only run on mount and unmount | |
}, []); | |
return screen; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment