Skip to content

Instantly share code, notes, and snippets.

@erictherobot
Created April 30, 2021 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erictherobot/c8e14442b13198d36b9cbab8481b6c92 to your computer and use it in GitHub Desktop.
Save erictherobot/c8e14442b13198d36b9cbab8481b6c92 to your computer and use it in GitHub Desktop.
Screen Width & Height Hook
import { useState, useEffect } from 'react';
export function useScreen() {
const getScreen = () => {
if (typeof window !== 'undefined') {
return window.screen;
}
return undefined;
};
const [screen, setScreen] = useState<Screen | undefined>(getScreen());
useEffect(() => {
function handleResize() {
setScreen(getScreen());
}
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
// Empty array ensures that effect is only run on mount and unmount
}, []);
return screen;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment