whalebeings.com

Mastering React Idle Timer: A Thorough Overview of Its Features

Written on

Introduction to Idle Logout

Idle logout functions as a crucial security feature in applications by automatically signing out users after a specified period of inactivity. This is especially significant for applications that handle sensitive data, as it helps prevent unauthorized access or misuse if a user forgets to log out.

Typically, an idle logout system initiates a timer when user activity is detected. If the user becomes inactive and the timer hits a designated limit, the application logs the user out, necessitating a new login to regain access.

Implementing idle logout requires both front-end and back-end efforts. On the front-end, user interactions can be tracked through various events like mouse movements, clicks, or keyboard activity. The back-end monitors the user's last activity and terminates the session if no new actions are recorded within a set timeframe.

An example of how an idle timer functions in JavaScript is shown below, which closely monitors user inactivity and triggers a logout process after a defined period of idleness:

const TIMEOUT = 15 * 60 * 1000; // 15 minutes

const idleTimer = () => {

let timer;

window.onload = resetTimer;

// tracking events

document.onmousemove = resetTimer;

document.onkeydown = resetTimer;

const logout = () => {

alert('You have been logged out!');

}

const resetTimer = () => {

clearTimeout(timer);

timer = setTimeout(logout, TIMEOUT);

}

};

The React Idle Timer library is a robust solution for managing idle time. NPM trends reveal that react-idle-timer is a dominant choice among React idle timer libraries. Its extensive features, user-friendliness, and popularity in the development community make it an excellent option for handling inactivity in React applications.

React Idle Timer Features Overview

Understanding React Idle Timer

In this article, we will explore how the react-idle-timer operates, offering an in-depth understanding of its functionality and implementation.

Setting Up React Idle Timer

To get started, we will create a Vite application to experiment with React Idle Timer. Use the following command to set up a new React project:

% yarn create vite vite-idle-timer --template react-ts

% cd vite-idle-timer

To add React Idle Timer, execute the command below for installation:

% yarn add react-idle-timer

You will see react-idle-timer listed in your package.json dependencies:

"dependencies": {

"react": "^18.2.0",

"react-dom": "^18.2.0",

"react-idle-timer": "^5.7.2",

}

The useIdleTimer Hook

The useIdleTimer hook serves as the primary method for detecting user inactivity. Below is its definition:

function useIdleTimer({ timeout, promptTimeout, promptBeforeIdle, element, events, timers, immediateEvents, onPresenceChange, onPrompt, onIdle, onActive, onAction, onMessage, debounce, throttle, eventsThrottle, startOnMount, startManually, stopOnIdle, crossTab, name, syncTimers, leaderElection, disabled }?: IIdleTimerProps): IIdleTimer

This hook includes parameters such as timeout duration and functions that execute when the user becomes idle or active.

Idle Detection Mechanism

The core functionality of React Idle Timer is to detect user inactivity. It monitors specific events and alerts the application if the user fails to interact within a defined timeframe.

The modified src/App.tsx file below demonstrates an idle timeout set to 10 seconds:

import { useEffect, useState } from 'react';

import { useIdleTimer } from 'react-idle-timer';

function App() {

const [state, setState] = useState('Active');

const [eventInfo, setEventInfo] = useState('No event');

const [remaining, setRemaining] = useState(0);

const onIdle = () => {

setState('Idle');

};

const onActive = () => {

setState('Active');

};

const onAction = (event) => {

if (event) {

setEventInfo(The event ${event.type} occurred at ${new Date});

}

};

const { getRemainingTime } = useIdleTimer({

onIdle,

onActive,

onAction,

timeout: 10_000,

throttle: 500,

});

useEffect(() => {

const interval = setInterval(() => {

setRemaining(Math.ceil(getRemainingTime() / 1000));

}, 500);

return () => {

clearInterval(interval);

};

});

return (

<>

React Idle Timer

useIdleTimer

Current State: {state}

{eventInfo}

{remaining} seconds remaining

</>

);

}

export default App;

Upon executing the yarn dev command, the onAction callback updates based on user activity. If inactivity persists for 10 seconds, the getRemainingTime method indicates zero time left, subsequently triggering the onIdle callback.

Confirm Prompt Feature

A common application for an idle timer is to identify user inactivity and prompt them to confirm their presence. This feature is now integrated into the core functionalities of React Idle Timer.

The src/App.tsx file below includes the confirmation prompt that activates when there are 5 seconds left:

import { useEffect, useState } from 'react';

import { useIdleTimer } from 'react-idle-timer';

function App() {

const [state, setState] = useState('Active');

const [eventInfo, setEventInfo] = useState('No event');

const [remaining, setRemaining] = useState(0);

const [prompt, setPrompt] = useState('');

const onIdle = () => {

setState('Idle');

setPrompt('');

};

const onActive = () => {

setState('Active');

setPrompt('');

};

const onAction = (event) => {

if (event) {

setEventInfo(The event ${event.type} happened at ${new Date});

}

};

const onPrompt = () => {

setPrompt('You are about to enter the Idle state');

};

const { getRemainingTime } = useIdleTimer({

onIdle,

onActive,

onAction,

onPrompt,

timeout: 10_000,

promptBeforeIdle: 5_000,

throttle: 500,

});

useEffect(() => {

const interval = setInterval(() => {

setRemaining(Math.ceil(getRemainingTime() / 1000));

}, 500);

return () => {

clearInterval(interval);

};

});

return (

<>

{prompt}

React Idle Timer

useIdleTimer

Current State: {state}

{eventInfo}

{remaining} seconds remaining

</>

);

}

export default App;

If no activity is detected for 5 seconds, a confirmation prompt is displayed. If the user interacts afterward, the prompt disappears. If inactivity continues, the prompt remains visible until the idle time hits 10 seconds, triggering the onIdle callback.

Cross-Tab Support

The cross-tab capability allows synchronization of events and states across multiple tabs running the application, enhancing user experience and enabling inter-tab communication.

The following commands set up an example demonstrating this feature using React Router 6, tailored for a Vite application:

% cd login-out-react-router

% yarn install

Here is the src/App.tsx file that establishes a main route, /main, with two subroutes: /one and /two. Unrecognized routes redirect users to a login page.

import { BrowserRouter, Routes, Route } from 'react-router-dom';

import { MainPage } from './MainPage';

import { PageOne, PageTwo } from './Pages';

import { Login } from './Login';

function App() {

return (

<BrowserRouter>

<Routes>

<Route path="/" element={<Login />} />

<Route path="/main" element={<MainPage />} />

<Route path="/one" element={<PageOne />} />

<Route path="/two" element={<PageTwo />} />

<Route path="*" element={<div>No page is selected</div>} />

</Routes>

</BrowserRouter>

);

}

export default App;

The Login.tsx file contains a button to navigate to the /main route:

import { useNavigate } from 'react-router-dom';

export const Login = () => {

const navigate = useNavigate();

return <button onClick={() => navigate('/main')}>Login</button>;

};

The src/Main.tsx file provides links to /one, /two, and a logout button:

import { Link, Outlet, useNavigate } from 'react-router-dom';

export const MainPage = () => {

const navigate = useNavigate();

return (

<>

<Link to="/one">Page One</Link>

<Link to="/two">Page Two</Link>

<button onClick={() => navigate('/')}>Logout</button>

<Outlet />

</>

);

};

After executing the yarn dev command, a successful login redirects users to the /main page, which includes links to Page One and Page Two. Clicking the Logout button returns the application to its pre-login state.

Creating a Custom Hook

We can create a custom hook called useConfiguredIdleTimer in the src/useConfiguredIdleTimer.ts file to navigate the application to the root route if the user is idle for 10 seconds across all tabs/windows:

import { useIdleTimer } from 'react-idle-timer';

import { useNavigate } from 'react-router-dom';

export const useConfiguredIdleTimer = () => {

const navigate = useNavigate();

useIdleTimer({

timeout: 10_000,

crossTab: true,

onIdle: () => {

navigate('/');

},

});

};

This hook is then added to the src/Main.tsx file as follows:

import { Link, Outlet, useNavigate } from 'react-router-dom';

import { useConfiguredIdleTimer } from './useConfiguredIdleTimer';

export const MainPage = () => {

useConfiguredIdleTimer();

const navigate = useNavigate();

return (

<>

<Link to="/one">Page One</Link>

<Link to="/two">Page Two</Link>

<button onClick={() => navigate('/')}>Logout</button>

<Outlet />

</>

);

};

Upon executing the yarn dev command, both browser windows can log in and navigate through various pages. After 10 seconds of inactivity, both windows will automatically log out of the application, showcasing the cross-tab functionality.

Conclusion

This article has highlighted the features of React Idle Timer, which stands out as a leading library for managing user inactivity. We demonstrated its capabilities, including idle detection, confirmation prompts, and cross-tab support. Its comprehensive features, intuitive interface, and popularity among developers make it an excellent choice for handling idle time in React applications.

Thanks for reading!

Want to Connect?

If you're interested, feel free to explore my collection of web development articles.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Taylor Swift's Legal Battle: A Stand Against AI Misuse

Taylor Swift's potential lawsuit highlights the dangers of AI misuse and deepfakes, urging accountability in the digital age.

Turning Pain into Purpose: Building Emotional Resiliency

Explore how emotional pain can lead to personal growth and resilience through reframing, learning, and self-care.

Unlocking the Power of Dreams for Self-Discovery and Growth

Explore how dreams can aid in self-discovery and goal achievement, enhancing personal growth and understanding.