Created
August 22, 2023 20:30
-
-
Save cleaver/353044cac426841577171c00d57d081c to your computer and use it in GitHub Desktop.
React hook for window resize + vertical scroll
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'; | |
export function useWindowPosition() { | |
const [windowSize, setWindowSize] = useState({ | |
width: 0, | |
height: 0, | |
scrollY: 0, | |
}); | |
function handleResize() { | |
setWindowSize({ | |
width: window.innerWidth, | |
height: window.innerHeight, | |
scrollY: window.scrollY, | |
}); | |
} | |
useEffect(() => { | |
window.addEventListener('resize', handleResize); | |
window.addEventListener('scroll', handleResize); | |
handleResize(); | |
return () => { | |
window.removeEventListener('resize', handleResize); | |
window.removeEventListener('scroll', handleResize); | |
}; | |
}, []); | |
return windowSize; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment