Created
May 23, 2024 21:34
-
-
Save Michal-Radomski/1107ad766f7f46aabba6384a7dbd44bd to your computer and use it in GitHub Desktop.
Custom React hook of inactivity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//* Based on useIdleTimer (TC-Webapp) | |
import React from "react"; | |
const useIdleTimerHook = (isActive: boolean, onIdle: Function, defaultTimeout_ms = 3600 * 1000): void => { | |
// console.log("isActive:", isActive); | |
const timerRef: React.MutableRefObject<number | null> = React.useRef<number | null>(null); | |
const resetTimer = React.useCallback(() => { | |
if (timerRef.current) { | |
clearTimeout(timerRef?.current); | |
} | |
timerRef.current = setTimeout(onIdle, defaultTimeout_ms); | |
}, [onIdle, defaultTimeout_ms]); | |
React.useEffect(() => { | |
if (isActive) { | |
const events: string[] = ["mousemove", "mousedown", "keypress", "scroll", "touchstart", "mouseup"]; | |
events.forEach((event) => window.addEventListener(event, resetTimer)); | |
resetTimer(); | |
return () => { | |
events.forEach((event) => window.removeEventListener(event, resetTimer)); | |
if (timerRef.current) { | |
clearTimeout(timerRef.current); | |
} | |
}; | |
} | |
}, [isActive, resetTimer]); | |
}; | |
export default useIdleTimerHook; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment