Idle timers are essential for web applications that handle sensitive user data or require authentication. By automatically detecting user inactivity and taking appropriate actions--such as logging out users or showing warnings--idle timers enhance security and improve user experience. This guide explores how to implement an idle timer in React using modern best practices and the react-idle-timer library.
What you'll learn:
- Installing and configuring react-idle-timer
- Implementing idle detection hooks
- Cross-tab synchronization patterns
- Integration with authentication systems
- Performance optimization techniques
Implementing proper session management is a fundamental aspect of professional web development that protects both users and applications from unauthorized access while maintaining a seamless user experience.
Secure your React applications with intelligent session management
Security Protection
Automatically log out users when they leave their devices unattended, preventing unauthorized access to sensitive data and functionality.
Session Compliance
Meet regulatory requirements for financial, healthcare, and enterprise applications that mandate automatic session timeout functionality.
Resource Optimization
Free server resources by closing connections and clearing session data for inactive users, improving application performance.
User Experience
Provide clear communication about session status with countdown warnings and extension options, balancing security with convenience.
Installing and Setting Up react-idle-timer
The react-idle-timer package provides a robust, well-maintained solution for implementing idle detection in React applications. Available through npm, this library offers both a hook-based API and a higher-order component pattern, making it compatible with various React application architectures.
Installation
npm install react-idle-timer
The package handles the complexity of tracking user activity across different event types and browser states, providing a reliable foundation for idle detection.
Basic Configuration Options
The useIdleTimer hook accepts several configuration options:
| Option | Description | Default |
|---|---|---|
timeout | Idle timeout duration in milliseconds | 1000 * 60 * 15 (15 min) |
events | Array of events to track for activity | Comprehensive default list |
onIdle | Callback when user becomes idle | undefined |
onActive | Callback when user returns from idle | undefined |
onAction | Callback when user triggers watched event | undefined |
crossTab | Enable cross-tab synchronization | false |
These configuration options allow you to tailor idle detection to your specific security requirements and user experience goals.
1import { useIdleTimer } from 'react-idle-timer';2 3const SessionManager = () => {4 const onIdle = () => {5 console.log('User is idle - initiating logout');6 logoutUser();7 };8 9 const onActive = (event) => {10 console.log('User returned from idle state');11 cancelPendingLogout();12 };13 14 const {15 isIdle,16 getRemainingTime,17 start,18 pause,19 reset20 } = useIdleTimer({21 onIdle,22 onActive,23 timeout: 1000 * 60 * 15, // 15 minutes24 });25 26 return (27 <div>28 {isIdle() && <SessionWarning />}29 </div>30 );31};Handling Different Event Types
The react-idle-timer library monitors a comprehensive set of events to detect user activity:
Default Events Tracked
- Mouse events: mousemove, mousedown, mouseup, scroll, wheel
- Keyboard events: keydown, keyup, keypress
- Touch events: touchstart, touchmove, touchend
- Visibility events: visibilitychange, focus, blur
Customizing Tracked Events
You can customize which events trigger activity detection:
const { reset } = useIdleTimer({
timeout: 1000 * 60 * 10,
events: ['mousemove', 'keydown', 'click']
});
This customization proves useful when your application includes automated interactions that shouldn't reset the idle timer, such as auto-saving drafts or refreshing data displays.
Performance Optimization
For high-frequency events, use throttling to reduce CPU usage:
const { reset } = useIdleTimer({
throttle: 1000, // Only process events once per second
timeout: 1000 * 60 * 15
});
Optimizing event handling is part of building performant React applications that scale effectively.
Advanced Features: Cross-Tab Synchronization
Cross-tab synchronization enables coordinated idle detection across multiple browser tabs running the same application. When users have your application open in multiple tabs, cross-tab synchronization ensures consistent idle state across all tabs.
How It Works
The cross-tab functionality uses the Broadcast Channel API and LocalStorage to communicate between tabs:
- Activity in one tab resets the idle timer in all tabs
- Logout in one tab logs out from all tabs
- Leader election handles timeout coordination
- Automatic fallback for older browsers
Implementation
const {
isIdle,
isLeader,
getTabId
} = useIdleTimer({
crossTab: true,
name: 'my-app-session',
timeout: 1000 * 60 * 15,
onIdle: () => logoutFromAllTabs()
});
Key Methods for Cross-Tab
isLeader(): Check if current tab is the leader for coordinationgetTabId(): Get unique identifier for this tab- Automatic synchronization of idle state across tabs
This advanced pattern is essential for AI-powered applications that manage sensitive user sessions across multiple interfaces.
Integration with Authentication Systems
Integrating idle timers with authentication systems requires coordination between session timeout logic and auth token management.
JWT-Based Authentication
const { onIdle } = useIdleTimer({
timeout: 1000 * 60 * 15,
onIdle: async () => {
// Clear tokens from storage
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
// Clear auth state
dispatch(logout());
// Redirect to login
router.push('/login?reason=idle');
}
});
Session Cookie Authentication
const { onIdle } = useIdleTimer({
timeout: 1000 * 60 * 15,
onIdle: async () => {
// Invalidate server-side session
await fetch('/api/auth/logout', { method: 'POST' });
// Redirect
router.push('/login');
}
});
Extending Sessions
Provide users the ability to extend their session before automatic logout:
const { reset, getRemainingTime } = useIdleTimer({
timeout: 1000 * 60 * 15,
onIdle: handleLogout
});
const handleExtendSession = async () => {
// Optionally refresh token server-side
await refreshAuthToken();
// Reset idle timer
reset();
};
Best Practices for React Idle Timers
Security Guidelines
- Timeout Duration: Match timeout to data sensitivity--shorter for financial/healthcare, longer for general use
- Warning Modal: Always show countdown warnings before automatic logout
- Token Cleanup: Clear all authentication tokens and session data on logout
- HTTPS Only: Ensure idle timer functionality works correctly with secure contexts
User Experience
// Multi-stage idle detection
const TIMEOUT = 1000 * 60 * 15; // 15 minutes
const WARNING_BEFORE = 1000 * 60 * 2; // 2 minute warning
const {
isIdle,
isPrompted
} = useIdleTimer({
timeout: TIMEOUT,
promptBeforeIdle: WARNING_BEFORE,
onIdle: handleLogout,
onPrompt: showCountdownModal
});
Performance Tips
- Throttle high-frequency events (mousemove, scroll) to reduce CPU usage
- Debounce keyboard events in text-heavy applications
- Close connections (WebSockets, SSE) when user becomes idle
- Clean up resources in onIdle callback to prevent memory leaks
Testing Considerations
- Test across different browsers and devices
- Verify behavior with multiple tabs open
- Test with various activity patterns (mouse only, keyboard only, mixed)
- Verify timeout accuracy under system load
Following these best practices ensures your session management aligns with comprehensive SEO strategies that prioritize both security and user experience.
Frequently Asked Questions
How long should the idle timeout be?
Timeout duration depends on your application's security requirements. Financial and healthcare applications typically use 5-15 minute timeouts. Less sensitive applications can use 20-30 minutes. Always provide a countdown warning before logout.
Does react-idle-timer work on mobile devices?
Yes, the library tracks touch events (touchstart, touchmove, touchend) for mobile support. Ensure your application handles these events correctly for accurate idle detection on touch devices.
How do cross-tab timers stay synchronized?
The library uses the Broadcast Channel API for modern browsers and falls back to LocalStorage events. This enables real-time communication between tabs running the same application.
Can I pause the idle timer programmatically?
Yes, the useIdleTimer hook returns pause() and resume() methods. You might use these during video playback or other activities where you want to extend the perceived active time.
What events does the idle timer track by default?
By default, it tracks: mousemove, keydown, wheel, DOMMouseScroll, mousewheel, mousedown, touchstart, touchmove, MSPointerDown, MSPointerMove, visibilitychange, and focus events.
Sources
- LogRocket: How to make an idle timer for your React app - Comprehensive tutorial covering react-idle-timer package usage
- IdleTimer.dev: useIdleTimer API Documentation - Official API documentation with complete props reference
- NPM: react-idle-timer - Package information and installation instructions