Created
March 7, 2022 17:29
-
-
Save tannerlinsley/8d122ceea8c229dc9f5da4ccb5e2acbf to your computer and use it in GitHub Desktop.
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
import * as React from 'react' | |
let activeTimeout = null | |
let reactivateFn = null | |
export function useOnIdle(fn, time) { | |
React.useEffect(() => { | |
const onUsage = () => { | |
if (reactivateFn) { | |
reactivateFn() | |
reactivateFn = null | |
} | |
if (activeTimeout) { | |
clearTimeout(activeTimeout) | |
} | |
activeTimeout = setTimeout(() => { | |
reactivateFn = fn() | |
if (reactivateFn !== 'function') { | |
reactivateFn = null | |
} | |
}, time) | |
} | |
const events = [ | |
'mousedown', | |
'mousemove', | |
'mouseup', | |
'mouseenter', | |
'mouseleave', | |
'keydown', | |
'keyup', | |
'touchstart', | |
'toucheend', | |
'touchmove', | |
] | |
events.forEach((event) => { | |
document.addEventListener(event, onUsage) | |
}) | |
return () => { | |
events.forEach((event) => { | |
document.removeEventListener(event, onUsage) | |
}) | |
} | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
}, [time]) | |
} | |
// Usage example | |
function App () { | |
useOnIdle(() => { | |
console.log('User is now idle') | |
return () => { | |
console.log('User is active again') | |
} | |
}, 1000 * 60 * 1000) // 10 minutes | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment