Skip to content

Instantly share code, notes, and snippets.

@ivanstnsk
Last active October 24, 2022 11:57
Show Gist options
  • Save ivanstnsk/c3ba1edf00d07fab9afa3f61a95193a8 to your computer and use it in GitHub Desktop.
Save ivanstnsk/c3ba1edf00d07fab9afa3f61a95193a8 to your computer and use it in GitHub Desktop.
use Window Resize hook React in Typescript
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