Installation
Props
| Prop | Type | Default | Description |
|---|---|---|---|
timeout | number | 1000 | The timeout in milliseconds |
options? | UseIdleOptions | The options for the hook |
Options
| Prop | Type | Default | Description |
|---|---|---|---|
events? | string[] | DEFAULT_EVENTS | The events to listen to |
initialState? | boolean | true | The initial state of the idle state |
Data
| Prop | Type | Description |
|---|---|---|
idle | boolean | Whether the user is idle for the given timeout |
reset | () => void | Resets the idle state |
Key Features & Details
Event Handling
- The hook listens to a configurable set of user events (e.g.,
keydown,mousemove,click, etc.) to detect activity. - You can customize the events via the
options.eventsarray.
Timer Logic
- The idle state is set to
trueif no activity is detected for the specifiedtimeout(in ms). - Any user activity resets the timer and sets
idletofalse. - The timer is initialized on mount and reset on every relevant event.
Reset Function
- The
resetfunction can be called manually to reset the idle timer and setidletofalse.
Cleanup
- All event listeners and timers are cleaned up automatically when the component unmounts.
Best Practices & Caveats
- The hook is client-side only; on the server, it does not track user activity.
- For best performance, avoid creating new event arrays on every render (use
useMemoif needed). - The hook is useful for auto-logout, UI dimming, or other inactivity features.
Examples
Basic Usage
const [idle, reset] = useIdle(2000);
if (idle) {
// Show idle warning or log out
}Custom Events
const [idle] = useIdle(3000, { events: ['mousemove', 'keydown'] });Manual Reset
const [idle, reset] = useIdle(5000);
<button onClick={reset}>Reset Idle Timer</button>;