Created
September 24, 2021 15:35
-
-
Save eriksachse/b596d6be54007f04bc2c8fee792a8fde to your computer and use it in GitHub Desktop.
get window size 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 default function useWindowDimensions() { | |
| const hasWindow = typeof window !== "undefined"; | |
| function getWindowDimensions() { | |
| const width = hasWindow ? window.innerWidth : null; | |
| const height = hasWindow ? window.innerHeight : null; | |
| return { | |
| width, | |
| height, | |
| }; | |
| } | |
| const [windowDimensions, setWindowDimensions] = useState( | |
| getWindowDimensions() | |
| ); | |
| useEffect(() => { | |
| if (hasWindow) { | |
| function handleResize() { | |
| setWindowDimensions(getWindowDimensions()); | |
| } | |
| window.addEventListener("resize", handleResize); | |
| return () => window.removeEventListener("resize", handleResize); | |
| } | |
| }, [hasWindow]); | |
| return windowDimensions; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage: