Created
January 26, 2023 07:23
-
-
Save JoueBien/c467e5fd6ea88e1b171a7448a4adead8 to your computer and use it in GitHub Desktop.
useScreenSize
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 { useEffect, useState } from "react"; | |
export function useScreenSize() { | |
// Local State | |
const [width, setWidth] = useState<number>(1200); | |
const [height, setHeight] = useState<number>(900); | |
// Update the height | |
function onScreenSizeChange(_event: Event) { | |
setWidth(window.innerWidth); | |
setHeight(window.innerHeight); | |
} | |
// On Mount subscribe to screen size changing | |
useEffect(() => { | |
window.addEventListener("resize", onScreenSizeChange); | |
// Clean up | |
return () => { | |
window.removeEventListener("resize", onScreenSizeChange); | |
}; | |
}, []); | |
return { | |
width, | |
height, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment