Last active
June 27, 2024 09:41
-
-
Save tilap/73f1eb081e29ff3b38c8fb236e474eea to your computer and use it in GitHub Desktop.
A simple react hook to get window size and listen to changes.
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 { 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