Skip to main content

useIdle

A custom hook that detects the user's idle state.

If there is no user activity for the specified duration, the state is considered idle. It detects various user activities such as mouse movements, keyboard input, and touch events. Page visibility changes are also detected, transitioning to active when the tab becomes visible again.


Detected User Activities

useIdle detects user activity through the following events:

  • mousemove - Mouse movement
  • mousedown - Mouse click
  • resize - Window resize
  • keydown - Keyboard input
  • touchstart - Touch start
  • wheel - Mouse wheel / scroll
  • visibilitychange - Tab switch (when the page becomes visible again)

All events are throttled to 500ms to prevent unnecessary event calls.


Use Cases

  • Auto logout functionality
  • Screensaver activation
  • User activity monitoring
  • Resource saving (stop API calls when idle)
  • Notification system (show notifications when user returns)

Code

🔗 View source code


Interface

typescript
interface UseIdleProps {
timeout: number; // time in milliseconds before considered idle
onIdle?: () => void; // callback when entering idle state
onActive?: () => void; // callback when entering active state
}
typescript
function useIdle({ timeout, onIdle, onActive }: UseIdleProps): boolean

Options

NameTypeDefaultDescription
timeoutnumber-Time in milliseconds before the user is considered idle
onIdle() => void-Callback invoked when entering idle state
onActive() => void-Callback invoked when entering active state

Usage

typescript
import { useIdle } from '@modern-kit/react';

const Example = () => {
const isIdle = useIdle({
timeout: 5000, // idle after 5 seconds
onIdle: () => {
console.log('User is idle');
},
onActive: () => {
console.log('User is active again');
}
});

return (
<div>
<p>Current status: {isIdle ? '😴 Idle' : '🟢 Active'}</p>
<p>Stop using the mouse or keyboard for 5 seconds!</p>
</div>
);
};

Example

Current status: 🟢 Active

Idle transitions: 0

Active transitions: 0

✨ Detects activity from mouse movements, keyboard input, scroll, and more

⏰ Becomes Idle after 3 seconds of inactivity

🔄 Switching tabs and returning also triggers Active state