MCPcopy Index your code
hub / github.com/streamich/react-use / useIdle

Function useIdle

src/useIdle.ts:8–58  ·  view source on GitHub ↗
(
  ms: number = oneMinute,
  initialState: boolean = false,
  events: string[] = defaultEvents
)

Source from the content-addressed store, hash-verified

6const oneMinute = 60e3;
7
8const useIdle = (
9 ms: number = oneMinute,
10 initialState: boolean = false,
11 events: string[] = defaultEvents
12): boolean => {
13 const [state, setState] = useState<boolean>(initialState);
14
15 useEffect(() => {
16 let mounted = true;
17 let timeout: any;
18 let localState: boolean = state;
19 const set = (newState: boolean) => {
20 if (mounted) {
21 localState = newState;
22 setState(newState);
23 }
24 };
25
26 const onEvent = throttle(50, () => {
27 if (localState) {
28 set(false);
29 }
30
31 clearTimeout(timeout);
32 timeout = setTimeout(() => set(true), ms);
33 });
34 const onVisibility = () => {
35 if (!document.hidden) {
36 onEvent();
37 }
38 };
39
40 for (let i = 0; i < events.length; i++) {
41 on(window, events[i], onEvent);
42 }
43 on(document, 'visibilitychange', onVisibility);
44
45 timeout = setTimeout(() => set(true), ms);
46
47 return () => {
48 mounted = false;
49
50 for (let i = 0; i < events.length; i++) {
51 off(window, events[i], onEvent);
52 }
53 off(document, 'visibilitychange', onVisibility);
54 };
55 }, [ms, events]);
56
57 return state;
58};
59
60export default useIdle;

Callers 1

DemoFunction · 0.90

Calls 3

onFunction · 0.90
offFunction · 0.90
setFunction · 0.70

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…