typescriptintermediate
useIdleDetection Hook
Detects user inactivity after a configurable timeout by monitoring mouse, keyboard, and touch events.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useState, useEffect, useRef, useCallback } from 'react';
export function useIdleDetection(timeoutMs = 300_000) {
const [isIdle, setIsIdle] = useState(false);
const timerRef = useRef<ReturnType<typeof setTimeout>>();
const resetTimer = useCallback(() => {
setIsIdle(false);
if (timerRef.current) clearTimeout(timerRef.current);
timerRef.current = setTimeout(() => setIsIdle(true), timeoutMs);
}, [timeoutMs]);
useEffect(() => {
const events = ['mousemove', 'keydown', 'touchstart', 'scroll'] as const;
events.forEach(e => window.addEventListener(e, resetTimer, { passive: true }));
resetTimer();
return () => {
events.forEach(e => window.removeEventListener(e, resetTimer));
if (timerRef.current) clearTimeout(timerRef.current);
};
}, [resetTimer]);
return isIdle;
}Use Cases
- Auto-logout
- Pausing expensive operations
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptbeginner
useTimeout Hook
Declarative setTimeout hook with automatic cleanup and reset capabilities.
Best for: Auto-dismiss notifications
#hooks#timer
typescriptintermediate
useFetch — Generic Data Fetching Hook
Custom React hook for data fetching with loading, error, and refetch states using the Fetch API.
Best for: API data fetching
#hooks#fetch
typescriptbeginner
useDebounce — Debounced Value Hook
Debounce any rapidly-changing value with a configurable delay. Useful for search inputs and resize handlers.
Best for: Search-as-you-type
#hooks#debounce
typescriptintermediate
useLocalStorage — Persistent State Hook
Sync React state with localStorage including SSR safety, JSON serialization, and cross-tab updates.
Best for: User preferences
#hooks#localstorage