From c826ad66df066b90b09009f2f4b83b56d018436e Mon Sep 17 00:00:00 2001 From: Armand Philippot Date: Wed, 15 Nov 2023 16:37:16 +0100 Subject: refactor(hooks): rewrite useScrollPosition hook * return the scroll position (both X and Y) * no longer accepts arguments * add tests --- .../use-scroll-position/use-scroll-position.ts | 31 ++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/utils/hooks/use-scroll-position/use-scroll-position.ts (limited to 'src/utils/hooks/use-scroll-position/use-scroll-position.ts') diff --git a/src/utils/hooks/use-scroll-position/use-scroll-position.ts b/src/utils/hooks/use-scroll-position/use-scroll-position.ts new file mode 100644 index 0000000..e20fda5 --- /dev/null +++ b/src/utils/hooks/use-scroll-position/use-scroll-position.ts @@ -0,0 +1,31 @@ +import { useCallback, useEffect, useState } from 'react'; + +export type ScrollPosition = { + x: number; + y: number; +}; + +const defaultPosition: ScrollPosition = { x: 0, y: 0 }; + +/** + * React hook to retrieve the current scroll position based on window. + * + * @returns {ScrollPosition} The scroll position. + */ +export const useScrollPosition = (): ScrollPosition => { + const [pos, setPos] = useState(defaultPosition); + + const updatePos = useCallback(() => { + setPos({ x: window.scrollX, y: window.scrollY }); + }, []); + + useEffect(() => { + if (typeof window === 'undefined') return undefined; + + window.addEventListener('scroll', updatePos); + + return () => window.removeEventListener('scroll', updatePos); + }, [updatePos]); + + return pos; +}; -- cgit v1.2.3