useIdle

A React hook that detects user inactivity after a configurable timeout.

Overview

useIdle monitors user activity (mouse, keyboard, touch, scroll) and triggers an idle state after a period of inactivity. Perfect for auto-logout, screensavers, pausing expensive operations, or energy-saving features.

Demo

💤 Sleepy Desktop

Stop moving for 3 seconds to see the screen go to sleep.

Interactive Scene
📁
Files
🌐
Browser
📧
Mail
📝
Notes
🎵
Music
⚙️
Settings
🏠
📁
🌐
📧
🎵
😴
Screen is sleeping...
Move mouse or press any key to wake
Status
✨ Awake
Idle Time
0s

API Reference

function useIdle(timeout?: number): {
  isIdle: boolean,
  lastActive: Date,
  idleTime: number
}

Parameters

NameTypeDescription
timeoutnumberOptional. Milliseconds of inactivity before idle. Default: 3000.

Returns

NameTypeDescription
isIdlebooleantrue when user has been inactive for the timeout duration.
lastActiveDateTimestamp of the last detected activity.
idleTimenumberMilliseconds since the user became idle.

Usage Examples

Auto-Logout

import { useIdle } from 'react-hooks-ts'
 
function SessionManager() {
  const { isIdle, idleTime } = useIdle(300000) // 5 minutes
 
  useEffect(() => {
    if (isIdle && idleTime > 300000) {
      logout()
    }
  }, [isIdle, idleTime])
 
  return isIdle && <Warning>You will be logged out soon...</Warning>
}

Pause Video

import { useIdle } from 'react-hooks-ts'
 
function VideoPlayer() {
  const { isIdle } = useIdle(10000) // 10 seconds
 
  return (
    <video paused={isIdle}>
      {/* Video content */}
    </video>
  )
}

Features

  • 👁️ Activity Detection - Monitors mouse, keyboard, touch, and scroll.
  • ⏱️ Configurable Timeout - Set custom idle thresholds.
  • 📊 Idle Duration - Track how long user has been idle.
  • Optimized Listeners - Uses passive event listeners.