TimerBeginnerSSR-safehooks/timer/useIdleTimer.ts

useIdleTimer

Detect user idle time.

Import

TypeScript
import { useIdleTimer } from '@/hooks';

API

Signature

useIdleTimer(options?) → { isIdle, lastActive, reset }

When to use

Use useIdleTimer instead of re-implementing the same pattern in multiple components.

SSR / Next.js

Timers start in effects — no server timers.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useIdleTimer
Editor
function SessionGuard() {
  const { isIdle, reset } = useIdleTimer({
    timeout: 5 * 60_000,
    onIdle: () => console.log('lock screen'),
  });
  return <p>{isIdle ? 'Idle' : 'Active'} <button onClick={reset}>Nudge</button></p>;
}
Preview

Implementation source

Full library source for useIdleTimer — copy into your project when you are not installing a package yet.

hooks/timer/useIdleTimer.ts
import { useCallback, useEffect, useRef, useState } from 'react';
import { isBrowser } from '../utility/isBrowser';
import { useLatest } from '../utility/useLatest';

export interface UseIdleTimerOptions {
  /** Idle timeout in ms. @default 60000 */
  timeout?: number;
  onIdle?: () => void;
  onActive?: () => void;
  events?: string[];
  /** @default true */
  enabled?: boolean;
}

const DEFAULT_EVENTS = [
  'mousemove',
  'mousedown',
  'keydown',
  'touchstart',
  'scroll',
  'wheel',
] as const;

/** Detects user idle activity with configurable timeout. */
export function useIdleTimer(options: UseIdleTimerOptions = {}) {
  const {
    timeout = 60_000,
    onIdle,
    onActive,
    events = [...DEFAULT_EVENTS],
    enabled = true,
  } = options;

  const [isIdle, setIsIdle] = useState(false);
  const [lastActive, setLastActive] = useState(() => Date.now());
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const onIdleRef = useLatest(onIdle);
  const onActiveRef = useLatest(onActive);

  const clear = useCallback(() => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = null;
    }
  }, []);

  const goIdle = useCallback(() => {
    setIsIdle(true);
    onIdleRef.current?.();
  }, [onIdleRef]);

  const reset = useCallback(() => {
    clear();
    setLastActive(Date.now());
    setIsIdle((prev) => {
      if (prev) onActiveRef.current?.();
      return false;
    });
    timerRef.current = setTimeout(goIdle, timeout);
  }, [clear, goIdle, timeout, onActiveRef]);

  useEffect(() => {
    if (!isBrowser() || !enabled) {
      clear();
      return;
    }
    reset();
    const handler = () => reset();
    events.forEach((e) => window.addEventListener(e, handler, { passive: true }));
    return () => {
      clear();
      events.forEach((e) => window.removeEventListener(e, handler));
    };
  }, [enabled, events, reset, clear]);

  return { isIdle, lastActive, reset };
}

Copy-paste example

useIdleTimer.example.tsx
'use client';

import { useIdleTimer } from '@/hooks';

export function SessionGuard() {
  const { isIdle, reset } = useIdleTimer({
    timeout: 5 * 60_000,
    onIdle: () => console.log('lock screen'),
  });
  return <p>{isIdle ? 'Idle' : 'Active'} <button onClick={reset}>Nudge</button></p>;
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Pass null delay to pause/disable intervals and timeouts without unmounting.
  • Source of truth: open hooks/timer/useIdleTimer.ts for implementation details