Created
January 7, 2024 08:28
-
-
Save GalindoSVQ/7fea2b5de7b229a6a9b7af3b98c5a44d to your computer and use it in GitHub Desktop.
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 * as React from 'react'; | |
export function useWindowScroll() { | |
const [state, setState] = React.useState({ | |
x: null, | |
y: null, | |
}); | |
const scrollTo = React.useCallback((...args) => { | |
if (typeof args[0] === 'object') { | |
window.scrollTo(args[0]); | |
} else if (typeof args[0] === 'number' && typeof args[1] === 'number') { | |
window.scrollTo(args[0], args[1]); | |
} else { | |
throw new Error(`Invalid arguments passed to scrollTo`); | |
} | |
}, []); | |
React.useLayoutEffect(() => { | |
const handleScroll = () => { | |
setState({ x: window.scrollX, y: window.scrollY }); | |
}; | |
handleScroll(); | |
window.addEventListener('scroll', handleScroll); | |
return () => { | |
window.removeEventListener('scroll', handleScroll); | |
}; | |
}, []); | |
return [state, scrollTo]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://stackblitz.com/edit/stackblitz-starters-6tcuqz