Skip to content

Instantly share code, notes, and snippets.

@ali-sabry
Created April 5, 2023 16:07
Show Gist options
  • Save ali-sabry/d38e19a81081d1fb61fd76e6042d2304 to your computer and use it in GitHub Desktop.
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.
//=== 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