Skip to content

Instantly share code, notes, and snippets.

@andresgcarmona
Created October 24, 2022 15:05
Show Gist options
  • Save andresgcarmona/c72487bd94f4eaacf3412605a2941ca2 to your computer and use it in GitHub Desktop.
Save andresgcarmona/c72487bd94f4eaacf3412605a2941ca2 to your computer and use it in GitHub Desktop.
React hook that returns the window size
unction useWindowSize() {
const [windowSize, setWindowSize] = useState({
width: undefined,
height: undefined,
});
useEffect(() => {
// only execute all the code below in client side
if (typeof window !== 'undefined') {
// Handler to call on window resize
function handleResize() {
// Set window width/height to state
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
}
// Add event listener
window.addEventListener("resize", handleResize);
// Call handler right away so state gets updated with initial window size
handleResize();
// Remove event listener on cleanup
return () => window.removeEventListener("resize", handleResize);
}
}, []); // Empty array ensures that effect is only run on mount
return windowSize;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment