Created
April 5, 2023 16:07
-
-
Save ali-sabry/d38e19a81081d1fb61fd76e6042d2304 to your computer and use it in GitHub Desktop.
useIdleTimer custom hook: This hook provides a way to detect when the user has been idle (not interacting with the app) for a certain amount of time. It can be useful for triggering automatic logouts or other actions after a period 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
//=== Custom Hook useIdleTimer | |
import { useEffect, useState } from 'react'; | |
const useIdleTimer = (timeIdleMS) => { | |
const [isIdle, setIsIdle] = useState(false); | |
useEffect(() => { | |
let idleTimer; | |
const resetIdleTimer = () => { | |
clearTimeout(idleTimer); | |
idleTimer = setTimeout(() => { | |
setIsIdle(true); | |
}, timeIdleMS); | |
}; | |
resetIdleTimer(); | |
const onActivity = () => { | |
setIsIdle(false); | |
resetIdleTimer(); | |
}; | |
window.addEventListener('mousemove', onActivity); | |
window.addEventListener('scroll', onActivity); | |
window.addEventListener('keydown', onActivity); | |
return () => { | |
clearTimeout(idleTimer); | |
window.removeEventListener('mousemove', onActivity); | |
window.removeEventListener('scroll', onActivity); | |
window.removeEventListener('keydown', onActivity); | |
}; | |
}, [timeIdleMS]); | |
return isIdle; | |
}; | |
const App = () => { | |
const isIdle = useIdleTimer(5000); // 5 seconds of inactivity | |
useEffect(() => { | |
if (isIdle) { | |
console.log('User is idle for 5 seconds!'); | |
// Add your logout or other action here | |
} | |
}, [isIdle]); | |
return <div>Hello World</div>; | |
}; | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment