Created
November 28, 2019 23:52
-
-
Save chriskavanagh/f05528c9737ebad90b00e4f4802676a9 to your computer and use it in GitHub Desktop.
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 App() { | |
const size = useWindowSize(); | |
return ( | |
<div> | |
{size.width}px / {size.height}px | |
</div> | |
); | |
} | |
// Hook | |
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment