use-idle

Detect if user does nothing on page

Usage

use-idle detects if user does nothing for given time in ms:

Current state: idle

Custom events

By default, hook will listen to keypress, mousemove, touchmove, click and scroll events to set idle status. To change that provide a list of events in the options argument:

import { Badge } from "@bigcomponents/core";
import { useIdle } from "@bigcomponents/hooks";
 
function Demo() {
  const idle = useIdle(2000, { events: ["click", "touchstart"] });
 
  return (
    <Badge variant={idle ? "default" : "secondary"}>
      Current state: {idle ? "idle" : "not idle"}
    </Badge>
  );
}

Initial state

By default, the hook will return an idle state. To change that provide an initial state value in the options argument:

import { Badge } from "@bigcomponents/core";
import { useIdle } from "@bigcomponents/hooks";
 
function Demo() {
  const idle = useIdle(2000, { initialState: false });
 
  return (
    <Badge variant={idle ? "default" : "secondary"}>
      Current state: {idle ? "idle" : "not idle"}
    </Badge>
  );
}

Definition

function useIdle(
  timeout: number,
  options?: Partial<{ events: string[]; initialState: boolean }>
): boolean;