useInactivityTimeout – Session Timeout Hook for React
Overview
Countdown-based session/inactivity manager with a warning phase. Built on useIdleVisibility.
- After
timeout - warningBeforems of inactivity, the hook enters the warning phase and starts a per-second countdown. - When the countdown hits zero,
onTimeoutfires andisTimedOutbecomestrue. - Any user interaction (or calling
resetTimer) resets everything.
Usage
import { useInactivityTimeout } from "react-visibility-hooks";
function SessionManager() { const { isWarning, isTimedOut, remainingSeconds, resetTimer } = useInactivityTimeout({ timeout: 300_000, // 5 minutes warningBefore: 60_000, // warn 1 minute before onWarning: () => showWarningToast(), onTimeout: () => logout(), });
if (isTimedOut) return <p>Session expired.</p>;
if (isWarning) { return ( <div> <p>Session expires in {remainingSeconds}s</p> <button onClick={resetTimer}>Stay logged in</button> </div> ); }
return null;}API
Parameters
| Parameter | Type | Description |
|---|---|---|
options | InactivityTimeoutOptions? | Configuration |
Options (InactivityTimeoutOptions)
| Option | Type | Default | Description |
|---|---|---|---|
timeout | number | 300_000 | Total inactivity before timeout (ms) |
warningBefore | number | 60_000 | How long before timeout to start warning (ms). Set to 0 to disable. |
onTimeout | () => void | — | Called when the full timeout elapses |
onWarning | () => void | — | Called when entering the warning phase |
Returns (InactivityTimeoutResult)
| Property | Type | Description |
|---|---|---|
idle | boolean | true once the user has been idle long enough |
visible | boolean | Current page-visibility state |
isWarning | boolean | true during the warning countdown |
isTimedOut | boolean | true after the full timeout has elapsed |
remainingSeconds | number | Seconds until timeout (-1 when the user is not idle) |
resetTimer | () => void | Manually reset the timer and cancel pending timeout |