Skip to content

Instantly share code, notes, and snippets.

@GalindoSVQ
Created January 7, 2024 08:28
Show Gist options
  • Save GalindoSVQ/7fea2b5de7b229a6a9b7af3b98c5a44d to your computer and use it in GitHub Desktop.
Save GalindoSVQ/7fea2b5de7b229a6a9b7af3b98c5a44d to your computer and use it in GitHub Desktop.
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];
}
@GalindoSVQ
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment