Skip to content

Instantly share code, notes, and snippets.

@tannerlinsley
Created March 7, 2022 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tannerlinsley/8d122ceea8c229dc9f5da4ccb5e2acbf to your computer and use it in GitHub Desktop.
Save tannerlinsley/8d122ceea8c229dc9f5da4ccb5e2acbf to your computer and use it in GitHub Desktop.
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