Last active
February 11, 2019 04:45
-
-
Save joshuacerbito/27cf18fa7329d730c0cc005a3c67f5d5 to your computer and use it in GitHub Desktop.
Custom React hook for reading the window's dimension
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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