Skip to content

Instantly share code, notes, and snippets.

@antoniocapelo
Created April 10, 2019 22:32
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 antoniocapelo/19cd86cf9677258e54732ca606faa3b9 to your computer and use it in GitHub Desktop.
Save antoniocapelo/19cd86cf9677258e54732ca606faa3b9 to your computer and use it in GitHub Desktop.
Custom React Hook for setting a window resize listener and get updated dimensions
const useWindowSize = () => {
const [dimensions, setDimension] = useState({
width: window.innerWidth,
height: window.innerHeight,
});
useEffect(() => {
const handler = () => {
const {innerWidth, innerHeight} = window;
setDimension({ width: innerWidth, height: innerHeight})
};
window.addEventListener('resize', handler);
return () => window.removeEventListener(handler);
}, []);
return {
width: dimensions.width,
height: dimensions.height,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment