blob: e20fda5dae0a13dda57f1c38bfe031f2775256bc (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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;
};
|