-
Notifications
You must be signed in to change notification settings - Fork 6.5k
Expand file tree
/
Copy pathuseScroll.ts
More file actions
63 lines (51 loc) · 1.5 KB
/
useScroll.ts
File metadata and controls
63 lines (51 loc) · 1.5 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
'use client';
import { useEffect, useRef } from 'react';
import type { RefObject } from 'react';
type ScrollPosition = {
x: number;
y: number;
};
type UseScrollOptions = {
debounceTime?: number;
onScroll?: (position: ScrollPosition) => void;
};
// Custom hook to handle scroll events with optional debouncing
const useScroll = <T extends HTMLElement>(
ref: RefObject<T | null>,
{ debounceTime = 300, onScroll }: UseScrollOptions = {}
) => {
const timeoutRef = useRef<NodeJS.Timeout | undefined>(undefined);
useEffect(() => {
// Get the current element
const element = ref.current;
// Return early if no element or onScroll callback is provided
if (!element || !onScroll) {
return;
}
// Debounced scroll handler
const handleScroll = () => {
// Clear existing timeout
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
// Set new timeout to call onScroll after debounceTime
timeoutRef.current = setTimeout(() => {
if (element) {
onScroll({
x: element.scrollLeft,
y: element.scrollTop,
});
}
}, debounceTime);
};
element.addEventListener('scroll', handleScroll, { passive: true });
return () => {
element.removeEventListener('scroll', handleScroll);
// Clear any pending debounced calls
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, [ref, onScroll, debounceTime]);
};
export default useScroll;