Skip to content

Instantly share code, notes, and snippets.

@joshuacerbito
Last active February 11, 2019 04:45
Show Gist options
  • Save joshuacerbito/27cf18fa7329d730c0cc005a3c67f5d5 to your computer and use it in GitHub Desktop.
Save joshuacerbito/27cf18fa7329d730c0cc005a3c67f5d5 to your computer and use it in GitHub Desktop.
Custom React hook for reading the window's dimension
/**
* useWindowDimension React custom hook
* Usage:
* const { width, height } = useWindowDimension();
*/
import { useState, useEffect } from "react";
export function useWindowDimension() {
const [width, setWidth] = useState(window.innerWidth);
const [height, setHeight] = useState(window.innerHeight);
const listener = () => {
setWidth(window.innerWidth);
setHeight(window.innerHeight);
};
useEffect(() => {
window.addEventListener("resize", listener);
return () => {
window.removeEventListener("resize", listener);
};
}, []);
return {
width,
height
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment