Last active
October 24, 2022 11:57
-
-
Save ivanstnsk/c3ba1edf00d07fab9afa3f61a95193a8 to your computer and use it in GitHub Desktop.
use Window Resize hook React in Typescript
This file contains 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'; | |
type TWindowSize = [number, number]; | |
type THook = TWindowSize; | |
export const useWindowResize = (): THook => { | |
const initSize: TWindowSize = [ | |
window.innerWidth, | |
window.innerHeight, | |
]; | |
const [windowSize, setWindowSize] = useState<TWindowSize>(initSize); | |
useEffect(() => { | |
const handleResize = (): void => { | |
setWindowSize([ | |
window.innerWidth, | |
window.innerHeight, | |
]); | |
}; | |
window.addEventListener('resize', handleResize); | |
return () => { | |
window.removeEventListener('resize', handleResize); | |
}; | |
}, []); | |
return windowSize; | |
}; | |
// Example of usage | |
// const [width, height] = useWindowResize(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment