react-idle-timer
repository·master·Indexed 22 days ago
https://github.com/supremetechnopriest/react-idle-timerActivity detection for React.js applications. This library monitors user interactions such as mouse movements, key presses, and clicks to trigger actions when a user becomes idle, enabling features like automatic session timeouts, inactivity warnings, and auto-logout.
What's inside react-idle-timer
- React Idle Timer is a library designed to detect user inactivity in React applications. It allows developers to monitor user interactions (like mouse movements, key presses, or clicks) and trigger specific actions when a user becomes idle for a defined period. This is commonly used for security features like auto-logout, session management, or displaying inactivity warnings.
How Activity Detection works in react-idle-timer
masterActivity Detection is a feature that notifies you whenever a watched event is triggered, independent of whether that event actually changes the idle state. This allows you to track user interactions (like clicks or keystrokes) even if they don't reset the idle timer.How idle detection works in react-idle-timer
masterIdle detection is the core feature ofreact-idle-timer. It tracks user activity by listening to specific DOM events (like mouse movements, key presses, or scrolls) on a target element. When the user fails to trigger these events within a specifiedtimeoutperiod, the library identifies the user as 'idle'. It can also track 'presence' (the transition between active and idle states) and provide callbacks when these states change.Configure Cross Tab functionality in v5
masterThe Cross Tab API has been simplified in v5. The
crossTabprop now accepts abooleanto enable or disable the feature. Most configuration options from v4 are now set to sane defaults.Syncing Timers
Use the
syncTimersproperty (anumberrepresenting milliseconds) to replicate user actions across all tabs, keeping timeouts in sync. A value of200is a recommended starting point to balance synchronization with messaging overhead.Isolating Instances
If using multiple
IdleTimerinstances on the same page, use thenameprop to ensure cross-tab events are isolated to their respective instances.// Hook with Cross Tab and Syncing enabled const idleTimer = useIdleTimer({ crossTab: true, syncTimers: 200 }) // Multiple isolated instances const logoutTimer = useIdleTimer({ timeout: 1000 * 60 * 30, crossTab: true, syncTimers: 200, name: 'logout-timer' }) const activityTimer = useIdleTimer({ timeout: 1000 * 60 * 5, crossTab: true, syncTimers: 200, name: 'activity-timer' })Implement Integrated Prompting
masterYou can automatically prompt a user before they go idle (e.g., showing a modal to ask if they are still there).
Key properties and methods:
promptBeforeIdle: The amount of time (in ms) before thetimeoutis reached that the prompt should trigger.onPrompt(): Event handler called when the prompt state is entered. All other events are disabled while the prompt is active.onIdle(): Event handler called when the fulltimeoutis reached.onActive(): Event handler called if the user interacts/activates while in the prompted state.isPrompted(): State getter to check if the user is currently in the prompted state.getRemainingTime(): Returns the remaining time until the idle state is reached.activate(): Manually resets the timer and triggersonActiveif the user was idle or prompted.
export function App () { const timeout = 1000 * 60 * 30 const promptBeforeIdle = 1000 * 30 const [open, setOpen] = useState(false) const [remaining, setRemaining] = useState(0) const onPrompt = () => { setOpen(true) setRemaining(promptTimeout) } const onIdle = () => { setOpen(false) setRemaining(0) } const onActive = () => { setOpen(false) setRemaining(0) } const { getRemainingTime, isPrompted, activate } = useIdleTimer({ timeout, promptBeforeIdle, onPrompt, onIdle, onActive }) const handleStillHere = () => { setOpen(false) activate() } useEffect(() => { const interval = setInterval(() => { if (isPrompted()) { setRemaining(Math.ceil(getRemainingTime() / 1000)) } }, 1000) return () => clearInterval(interval) }, [getRemainingTime, isPrompted]) return ( <div className='modal' style={{ display: open ? 'block': 'none' }}> <p>Logging you out in {remaining} seconds</p> <button onClick={handleStillHere}>Im Still Here</button> </div> ) }Use IdleTimerProvider to avoid prop drilling
masterInstead of passing the IdleTimer API through multiple layers of your component tree (prop drilling), use the
IdleTimerProviderto make the API available to all descendant components via React Context. This allows any child component to access idle state and methods directly.import { IdleTimerProvider } from 'react-idle-timer' function App() { return ( <IdleTimerProvider timeout={1000 * 60}> <Child /> </IdleTimerProvider> ) }Install react-idle-timer via npm or yarn
masterTo use IdleTimer in your React project, install the
react-idle-timerpackage using your preferred package manager.npm i react-idle-timer # or yarn add react-idle-timerFollow Git commit message guidelines
masterIdleTimer enforces strict commit message guidelines. Messages must use the present tense and imperative mood (e.g., "Add feature" instead of "Added feature"), and the first line must be 72 characters or less.
Every commit must start with an applicable emoji to categorize the change:
Emoji Token Purpose :art: :art:Improving code format/structure :stopwatch: :stopwatch:Improving performance :memo: :memo:Writing documentation :zap: :zap:Adding a new feature :sparkles: :sparkles:Enhancing an existing feature :lady_beetle: :lady_beetle:Fixing a bug :fire: :fire:Removing code or files :green_heart: :green_heart:Fixing the CI build :white_check_mark: :white_check_mark:Adding tests :lock: :lock:Dealing with security :arrow_up: :arrow_up:Upgrading dependencies :arrow_down: :arrow_down:Downgrading dependencies :shirt: :shirt:Removing linter warnings :shower: :shower:Generic cleanup Enable and configure the Cross Tab feature
masterThe Cross Tab feature allows you to reconcile events and state across multiple browser tabs running your application. It provides a messaging layer to broadcast messages to all tabs and includes features like leader election and timer synchronization.
To use this feature, you must enable the
crossTabproperty in your configuration. If you are running multiple idle timer instances on the same page, you must provide a uniquenamefor each instance to avoid collisions.// Example configuration concept <IdleTimer crossTab={true} name="my-unique-timer-name" syncTimers={true} leaderElection={true} />Use the withIdleTimer Higher Order Component
masterThe
withIdleTimerHigher Order Component (HOC) is designed for class-based React applications. It acceptsIIdleTimerPropsas configuration and injects theIIdleTimerinterface into the wrapped component. You can use it in two primary ways: as a standalone component or as an injector for your existing components.import { withIdleTimer } from 'react-idle-timer'Submit a Pull Request
masterOnce your changes are complete, follow these steps to submit a Pull Request (PR):
- Fill out the "Ready for review" template to explain your changes.
- Link the PR to an issue if you are solving a specific task.
- Enable the checkbox to "allow maintainer edits" so the branch can be updated for merging.
- Respond to reviews: Address comments or suggested changes. Mark conversations as resolved once they are addressed.
- Resolve conflicts: If merge issues arise, you may need to resolve conflicts manually.
Mock Timers for testing IdleTimer
masterIf you are using worker thread timers, you must mock them to ensure your test runner (like Jest) uses main thread timers instead. Use the
createMocksfunction exported fromreact-idle-timerwithin abeforeAllhook in your test setup file.import { createMocks } from 'react-idle-timer' beforeAll(createMocks)