Skip to content

Instantly share code, notes, and snippets.

@cleaver
Created August 22, 2023 20:30
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 cleaver/353044cac426841577171c00d57d081c to your computer and use it in GitHub Desktop.
Save cleaver/353044cac426841577171c00d57d081c to your computer and use it in GitHub Desktop.
React hook for window resize + vertical scroll
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