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.
function useIdle(timeout: number): boolean;
timeout is the inactivity threshold in milliseconds. The hook returns a single boolean: true when idle, false when active.
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)
mousemove, mousedown, keydown, touchstart, scroll, and resize. Subscribe to all of them on window.timeout with zero activity. A burst of events that keeps arriving faster than timeout should keep it active indefinitely.false immediately and start a fresh countdown.