Skip to content

useInactivityTimeout – Session Timeout Hook for React

Overview

Countdown-based session/inactivity manager with a warning phase. Built on useIdleVisibility.

  1. After timeout - warningBefore ms of inactivity, the hook enters the warning phase and starts a per-second countdown.
  2. When the countdown hits zero, onTimeout fires and isTimedOut becomes true.
  3. 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

ParameterTypeDescription
optionsInactivityTimeoutOptions?Configuration

Options (InactivityTimeoutOptions)

OptionTypeDefaultDescription
timeoutnumber300_000Total inactivity before timeout (ms)
warningBeforenumber60_000How long before timeout to start warning (ms). Set to 0 to disable.
onTimeout() => voidCalled when the full timeout elapses
onWarning() => voidCalled when entering the warning phase

Returns (InactivityTimeoutResult)

PropertyTypeDescription
idlebooleantrue once the user has been idle long enough
visiblebooleanCurrent page-visibility state
isWarningbooleantrue during the warning countdown
isTimedOutbooleantrue after the full timeout has elapsed
remainingSecondsnumberSeconds until timeout (-1 when the user is not idle)
resetTimer() => voidManually reset the timer and cancel pending timeout