useIdleLoading saved progress…

useIdle

Build a React hook that tracks whether the user has gone idle. useIdle(timeout) returns false while the user is active and flips to true once timeout milliseconds pass with no activity at all — no mouse movement, clicks, key presses, touches, scrolls, or window resizes. The moment any of those happen, the countdown restarts and the value snaps back to false. This is the pattern behind "you've been inactive — log out?" banners and auto-pausing video players.

Signature

function useIdle(timeout: number): boolean;

timeout is the inactivity threshold in milliseconds. The hook returns a single boolean: true when idle, false when active.

Examples

function SessionGuard() {
  // Considered idle after 30 seconds with no activity.
  const idle = useIdle(30000);

  return idle
    ? <Banner>Still there? You'll be logged out soon.</Banner>
    : <App />;
}
// timeout = 1000
// t=0    mount                          → false (active)
// t=1000 no activity for 1000ms         → true  (idle)
// t=1200 user moves the mouse           → false (active, timer restarts)
// t=2200 no activity since t=1200       → true  (idle again)

Notes

  • Any of these events count as activity: mousemove, mousedown, keydown, touchstart, scroll, and resize. Subscribe to all of them on window.
  • Every activity event resets the countdown. The hook goes idle only after a full timeout with zero activity. A burst of events that keeps arriving faster than timeout should keep it active indefinitely.
  • Activity wakes it up. If the hook is already idle and an event fires, it must flip back to false immediately and start a fresh countdown.
  • Clean up on unmount. Both the timer and every listener must be removed when the component unmounts — a leftover timer firing into a dead component is a bug.
  • Don't worry about throttling the activity handler or distinguishing event types — every listed event is treated identically.
Loading editor…