-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseIdle.ts
44 lines (36 loc) · 1 KB
/
useIdle.ts
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
import { useState, useEffect, useRef } from 'react';
const DEFAULT_EVENTS: (keyof DocumentEventMap)[] = [
'keypress',
'mousemove',
'touchmove',
'click',
'scroll',
];
const DEFAULT_OPTIONS = {
events: DEFAULT_EVENTS,
initialState: true,
};
export function useIdle(
timeout: number,
options?: Partial<{ events: (keyof DocumentEventMap)[]; initialState: boolean }>,
) {
const { events, initialState } = { ...DEFAULT_OPTIONS, ...options };
const [idle, setIdle] = useState<boolean>(initialState);
const timer = useRef<number>();
useEffect(() => {
const handleEvents = () => {
setIdle(false);
if (timer.current) {
window.clearTimeout(timer.current);
}
timer.current = window.setTimeout(() => {
setIdle(true);
}, timeout);
};
events.forEach(event => document.addEventListener(event, handleEvents));
return () => {
events.forEach(event => document.removeEventListener(event, handleEvents));
};
}, [timeout]);
return idle;
}