use-idle

Detects if the user does nothing on the page

Import

Usage

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

Current state: idle
import { Badge } from '@mantine/core';
import { useIdle } from '@mantine/hooks';

function Demo() {
  const idle = useIdle(2000);
  return <Badge color={idle ? 'blue' : 'teal'}>Current state: {idle ? 'idle' : 'not idle'}</Badge>;
}

Custom events

By default, the 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:

Current state: idle
import { Badge } from '@mantine/core';
import { useIdle } from '@mantine/hooks';

function Demo() {
  const idle = useIdle(2000, { events: ['click', 'touchstart'] });
  return <Badge color={idle ? 'blue' : 'teal'}>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:

Current state: not idle
import { Badge } from '@mantine/core';
import { useIdle } from '@mantine/hooks';

function Demo() {
  const idle = useIdle(2000, { initialState: false });
  return <Badge color={idle ? 'blue' : 'teal'}>Current state: {idle ? 'idle' : 'not idle'}</Badge>;
}

Definition

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