Implement a useIdle hook that detects user inactivity for a specified time. It listens for user interactions like mouse movements, keyboard presses, and touch events, and resets a timer whenever activity is detected.

We consider the user to be idle if there are no events of type events dispatched within ms milliseconds. Additionally, if the user has just switched from another tab to our tab (hint: the visibilitychange event), the user should not be considered idle.

exportdefaultfunction Component() {
const idle = useIdle();
return (
    <div>
      <p>Status: {idle ? 'Idle' : 'Active'}</p>
    </div>
  );
}

Arguments

  1. ms: number: The number of milliseconds to wait before considering the user idle. This defaults to 60_000 (1 minute)
  2. initialState: boolean: The initial idle state. This defaults to false
  3. events: (keyof WindowEventMap)[]: An array of event types that count as user activity. The default value is provided as the DEFAULT_EVENTS constant

Returns

The hook returns a boolean value that indicates whether the user is idle or not.

Notes

Editorial