Openstatus www.openstatus.dev
at 40ee67dc9bbbb4d39796e1b7e8b2ae17c61dd77e 41 lines 1.2 kB view raw
1// Props: https://github.com/uidotdev/usehooks/blob/90fbbb4cc085e74e50c36a62a5759a40c62bb98e/index.js#L1310 2 3import * as React from "react"; 4 5export function useWindowScroll() { 6 const [state, setState] = React.useState<{ 7 x: number | null; 8 y: number | null; 9 }>({ 10 x: null, 11 y: null, 12 }); 13 14 // biome-ignore lint/suspicious/noExplicitAny: <explanation> 15 const scrollTo = React.useCallback((...args: any[]) => { 16 if (typeof args[0] === "object") { 17 window.scrollTo(args[0]); 18 } else if (typeof args[0] === "number" && typeof args[1] === "number") { 19 window.scrollTo(args[0], args[1]); 20 } else { 21 throw new Error( 22 "Invalid arguments passed to scrollTo. See here for more info. https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo", 23 ); 24 } 25 }, []); 26 27 React.useLayoutEffect(() => { 28 const handleScroll = () => { 29 setState({ x: window.scrollX, y: window.scrollY }); 30 }; 31 32 handleScroll(); 33 window.addEventListener("scroll", handleScroll); 34 35 return () => { 36 window.removeEventListener("scroll", handleScroll); 37 }; 38 }, []); 39 40 return [state, scrollTo] as const; 41}