h3/use's logo

h3/use

Command Palette

Search for a command to run...

useIdle

Returns true if the user is idle for a given timeout.

useIdle
This component uses the useIdle hook to detect if the user is idle for a given timeout (2 seconds).
The user is

idle

Interact with the page (keyboard, mouse, scroll, etc) to reset the idle timer.

Installation

Props

PropTypeDefaultDescription
timeoutnumber1000The timeout in milliseconds
options?UseIdleOptionsThe options for the hook

Options

PropTypeDefaultDescription
events?string[]DEFAULT_EVENTSThe events to listen to
initialState?booleantrueThe initial state of the idle state

Data

PropTypeDescription
idlebooleanWhether the user is idle for the given timeout
reset() => voidResets 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.events array.

Timer Logic

  • The idle state is set to true if no activity is detected for the specified timeout (in ms).
  • Any user activity resets the timer and sets idle to false.
  • The timer is initialized on mount and reset on every relevant event.

Reset Function

  • The reset function can be called manually to reset the idle timer and set idle to false.

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 useMemo if 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>;