-
-
Save mortegac/2f332ed3da808b6bc9d52129b053b78a to your computer and use it in GitHub Desktop.
React Hook to detect user inactivity based on specified events like mouse movements, touch events or key presses
This file contains hidden or 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
import { useEffect, useState } from "react"; | |
const defaultEvents = [ | |
"mousemove", | |
"mousedown", | |
"touchstart", | |
"keydown", | |
"wheel", | |
"resize", | |
]; | |
interface UseIdleOptions { | |
timeout?: number; | |
events?: string[]; | |
} | |
const useIdle = ({ | |
timeout = 5000, | |
events = defaultEvents, | |
}: UseIdleOptions = {}) => { | |
const [isIdle, setIsIdle] = useState<boolean>(false); | |
useEffect(() => { | |
let timer: ReturnType<typeof setTimeout>; | |
const resetTimer = () => { | |
clearTimeout(timer); | |
setIsIdle(false); | |
timer = setTimeout(() => setIsIdle(true), timeout); | |
}; | |
// Initialize the timer | |
resetTimer(); | |
// Event handler to reset the timer on user activity | |
events.forEach((event) => window.addEventListener(event, resetTimer)); | |
// Cleanup function | |
return () => { | |
clearTimeout(timer); | |
events.forEach((event) => window.removeEventListener(event, resetTimer)); | |
}; | |
}, [timeout, events]); | |
return isIdle; | |
}; | |
export default useIdle; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment