Created
July 25, 2021 11:36
-
-
Save vaibhavpandeyvpz/3ef88b76dfb27b86cfec9b932a3ec522 to your computer and use it in GitHub Desktop.
React hook to track window resize events.
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
import { useEffect, useState } from 'react'; | |
/** | |
* @return {{width: Number, height: Number}} | |
*/ | |
function getWindowSize() { | |
return { | |
width: window.innerWidth, | |
height: window.innerHeight, | |
}; | |
} | |
/** | |
* @return {{width: Number, height: Number}} | |
*/ | |
function useWindowSize() { | |
const [size, setSize] = useState(getWindowSize()); | |
useEffect(() => { | |
const listener = () => setSize(getWindowSize()); | |
window.addEventListener('resize', listener); | |
return () => window.removeEventListener('resize', listener); | |
}, []); | |
return size; | |
} | |
export default useWindowSize; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment