Skip to content

Instantly share code, notes, and snippets.

@JoueBien
Created January 26, 2023 07:23
Show Gist options
  • Save JoueBien/c467e5fd6ea88e1b171a7448a4adead8 to your computer and use it in GitHub Desktop.
Save JoueBien/c467e5fd6ea88e1b171a7448a4adead8 to your computer and use it in GitHub Desktop.
useScreenSize
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