Skip to content
On this page

useIdle

useIdle tracks if the user is idle on the page.

Adds two new behaviors to your Stimulus controller: away and back.

Reference

useIdle(controller, options = {})

controller: A Stimulus Controller (usually 'this')

options:

OptionDescriptionDefault value
msTime in milliseconds after which to consider the user idle60e3 which translates to 60000 (one minute)
initialStateWhether to consider the user initially idlefalse
eventsArray of events to listen on to detect if the user is "active" on the page.['mousemove', 'mousedown', 'resize', 'keydown', 'touchstart', 'wheel']
dispatchEventWhether to dispatch away and back events.true
eventPrefixWhether to prefix the name of the dispatched events. Can be a boolean or a string.
- true prefix the event with the controller identifier user:away
- someString prefix the event with the given string someString:away
- false to remove prefix
true

Basic Example:

connect() {
  useIdle(this, { ms: 3000 });
}

Example with all options:

connect() {
  useIdle(this, { ms: 3000, initialState: true, events: ['click'], dispatchEvent: false, eventPrefix: false });
}

Usage

Composing

import { Controller } from '@hotwired/stimulus'
import { useIdle } from 'stimulus-use'

export default class extends Controller {
  connect() {
    useIdle(this)
  }

  away(event) {
    alert('Hey, wake up!')
  }

  back(event) {
    alert('Welcome back!')
  }
}

Extending a controller

import { IdleController } from 'stimulus-use'

export default class extends IdleController {
  away(event) {
    alert('Hey, wake up!')
  }

  back(event) {
    alert('Welcome back!')
  }
}

Events

This module adds away and back events that you may use to trigger stimulus actions

<div data-controller="user" data-action="user:away->user#logout">
   ...
</div>
// user_controller.js

export default class extends Controller {

  connect() {
    useIdle(this)
  }

  logout(event) {
    event.preventDefault()
    // do some actions to logout the user
  }
}