Skip to content

Instantly share code, notes, and snippets.

@tilap
Last active December 13, 2019 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tilap/73f1eb081e29ff3b38c8fb236e474eea to your computer and use it in GitHub Desktop.
Save tilap/73f1eb081e29ff3b38c8fb236e474eea to your computer and use it in GitHub Desktop.
A simple react hook to get window size and listen to changes.
import { useCallback, useState, useEffect } from 'react';
const isBrowser = typeof window !== 'undefined';
const getSize = () => {
if (isBrowser) {
return {
width: window.innerWidth,
height: window.innerHeight,
};
}
return {
width: undefined,
height: undefined,
};
}
const useWindowSize = () => {
const [windowSize, setWindowSize] = useState(getSize);
const handleResize = useCallback(() => setWindowSize(getSize()), [setWindowSize]);
useEffect(() => {
if (!isBrowser) {
return false;
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []); // eslint-disable-line react-hooks/exhaustive-deps
return windowSize;
};
export default useWindowSize;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment