Package react-idle-timer will do the work for you.
You can install it like this,
sudo npm install react-idle-timer
or
npm install react-idle-timer --save
Component Usage
import React, { Component } from 'react'
import IdleTimer from 'react-idle-timer'
export default class YourApp extends Component {
constructor(props) {
super(props)
this.idleTimer = null
this.handleOnAction = this.handleOnAction.bind(this)
this.handleOnActive = this.handleOnActive.bind(this)
this.handleOnIdle = this.handleOnIdle.bind(this)
}
render() {
return (
<div>
<IdleTimer
ref={ref => { this.idleTimer = ref }}
timeout={1000 * 60 * 15}
onActive={this.handleOnActive}
onIdle={this.handleOnIdle}
onAction={this.handleOnAction}
debounce={250}
/>
{/** Your app/component here. */}
</div>
)
}
handleOnAction (event) {
console.log('user did something', event)
}
handleOnActive (event) {
console.log('user is active', event)
console.log('time remaining', this.idleTimer.getRemainingTime())
}
handleOnIdle (event) {
console.log('user is idle', event)
console.log('last active', this.idleTimer.getLastActiveTime())
}
}
Hook Usage
import React from 'react'
import { useIdleTimer } from 'react-idle-timer'
import App from './App'
export default function (props) {
const handleOnIdle = event => {
console.log('user is idle', event)
console.log('last active', getLastActiveTime())
}
const handleOnActive = event => {
console.log('user is active', event)
console.log('time remaining', getRemainingTime())
}
const handleOnAction = event => {
console.log('user did something', event)
}
const { getRemainingTime, getLastActiveTime } = useIdleTimer({
timeout: 1000 * 60 * 15,
onIdle: handleOnIdle,
onActive: handleOnActive,
onAction: handleOnAction,
debounce: 500
})
return (
<div>
{/** Your app/component here. */}
</div>
)
}
They offer a lot of feature which you can read here on GitHub at react-idle-timer