### Full useIdleTimer example with all props and methods (defaults) Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/use-idle-timer.mdx Complete example showing all available props with their default values, plus all return methods. The idleTimer object is destructured to access methods like start, reset, pause, and more. ```js import { useIdleTimer } from 'react-idle-timer' export const App = () => { const onPresenceChange = (presence) => { // Handle state changes in one function } const onPrompt = () => { // Fire a Modal Prompt } const onIdle = () => { // Close Modal Prompt // Do some idle action like log out your user } const onActive = (event) => { // Close Modal Prompt // Do some active action } const onAction = (event) => { // Do something when a user triggers a watched event } const { start, reset, activate, pause, resume, isIdle, isPrompted, isLeader, isLastActiveTab, getTabId, getRemainingTime, getElapsedTime, getLastIdleTime, getLastActiveTime, getIdleTime, getTotalIdleTime, getActiveTime, getTotalActiveTime } = useIdleTimer({ onPresenceChange, onPrompt, onIdle, onActive, onAction, timeout: 1000 * 60 * 20, promptBeforeIdle: 0, events: [ 'mousemove', 'keydown', 'wheel', 'DOMMouseScroll', 'mousewheel', 'mousedown', 'touchstart', 'touchmove', 'MSPointerDown', 'MSPointerMove', 'visibilitychange', 'focus' ], immediateEvents: [], debounce: 0, throttle: 0, eventsThrottle: 200, element: document, startOnMount: true, startManually: false, stopOnIdle: false, crossTab: false, name: 'idle-timer', syncTimers: 0, leaderElection: false }) return ( ) } ``` -------------------------------- ### Full mock setup: jest.config.js and test.setup.js Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/testing.mdx Complete setup to test with IdleTimer. The jest.config.js adds the setup file to setupFilesAfterEnv, and test.setup.js combines createMocks and MessageChannel mocking with cleanup. ```javascript // // jest.config.js // export default { ...otherOptions, setupFilesAfterEnv: [ './test.setup.js' ] } ``` ```javascript // // test.setup.js // import { createMocks } from 'react-idle-timer' import { MessageChannel } from 'worker_threads' import { cleanup } from '@testing-library/react' beforeAll(() => { createMocks() global.MessageChannel = MessageChannel }) afterAll(cleanup) ``` -------------------------------- ### Install react-idle-timer with npm or yarn Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/installation.mdx Install IdleTimer inside your React project directory using either npm or yarn. ```bash npm i react-idle-timer ``` ```bash yarn add react-idle-timer ``` -------------------------------- ### Example onPresenceChange implementation Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/props.mdx Shows how to implement the onPresenceChange callback, importing the PresenceType and checking for idle, active, and prompted states. ```ts // Example onPresenceChange implementation import type { PresenceType } from 'react-idle-timer' const onPresenceChange = (presence: PresenceType) => { const isIdle = presence.type === 'idle' const isActive = presence.type === 'active' && !presence.prompted const isPrompted = presence.type === 'active' && presence.prompted } ``` -------------------------------- ### start Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/methods.mdx Resets the IdleTimer instance to its initial state and starts the timer. Returns a boolean denoting if the instance was started successfully. ```APIDOC ## start() ### Description Resets the IdleTimer instance to its initial state and starts the timer. Returns a boolean denoting if the instance was started successfully. ### Method start ### Signature `() => boolean` ### Returns - **boolean** - `true` if the instance was started successfully, `false` otherwise. ``` -------------------------------- ### Minimal useIdleTimer usage (bare essential configuration) Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/use-idle-timer.mdx Minimal example of using useIdleTimer with only onPresenceChange; returns an idleTimer object. ```js import { useIdleTimer } from 'react-idle-timer' export const App = () => { const onPresenceChange = (presence) => { // Handle state changes in one function } const idleTimer = useIdleTimer({ onPresenceChange }) return ( ) } ``` -------------------------------- ### useIdleTimer Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/use-idle-timer.mdx Documentation for the useIdleTimer React hook, including its props, return values, and usage examples. ```APIDOC ## useIdleTimer ### Description The `useIdleTimer` hook is a React hook for functional React components. It takes `IIdleTimerProps` as configuration options and returns an `IIdleTimer` object with methods and properties to manage idle state. ### Import ```js import { useIdleTimer } from 'react-idle-timer' ``` ### Usage A minimal example with the bare essential configuration. ```js import { useIdleTimer } from 'react-idle-timer' export const App = () => { const onPresenceChange = (presence) => { // Handle state changes in one function } const idleTimer = useIdleTimer({ onPresenceChange }) return ( ) } ``` A full example with all available props and methods. Props are set to their default value. ```js import { useIdleTimer } from 'react-idle-timer' export const App = () => { const onPresenceChange = (presence) => { // Handle state changes in one function } const onPrompt = () => { // Fire a Modal Prompt } const onIdle = () => { // Close Modal Prompt // Do some idle action like log out your user } const onActive = (event) => { // Close Modal Prompt // Do some active action } const onAction = (event) => { // Do something when a user triggers a watched event } const { start, reset, activate, pause, resume, isIdle, isPrompted, isLeader, isLastActiveTab, getTabId, getRemainingTime, getElapsedTime, getLastIdleTime, getLastActiveTime, getIdleTime, getTotalIdleTime, getActiveTime, getTotalActiveTime } = useIdleTimer({ onPresenceChange, onPrompt, onIdle, onActive, onAction, timeout: 1000 * 60 * 20, promptBeforeIdle: 0, events: [ 'mousemove', 'keydown', 'wheel', 'DOMMouseScroll', 'mousewheel', 'mousedown', 'touchstart', 'touchmove', 'MSPointerDown', 'MSPointerMove', 'visibilitychange', 'focus' ], immediateEvents: [], debounce: 0, throttle: 0, eventsThrottle: 200, element: document, startOnMount: true, startManually: false, stopOnIdle: false, crossTab: false, name: 'idle-timer', syncTimers: 0, leaderElection: false }) return ( ) } ``` ### Parameters #### Props (IIdleTimerProps) - **onPresenceChange** (function) - Required - Callback fired when presence changes (idle/active). - **onPrompt** (function) - Optional - Callback fired when the prompt is triggered. - **onIdle** (function) - Optional - Callback fired when the user becomes idle. - **onActive** (function) - Optional - Callback fired when the user becomes active. - **onAction** (function) - Optional - Callback fired when a watched event is triggered. - **timeout** (number) - Optional - Idle timeout in milliseconds. Default: `1000 * 60 * 20`. - **promptBeforeIdle** (number) - Optional - Time in milliseconds to prompt before idle. Default: `0`. - **events** (array) - Optional - List of events to watch. Default: `['mousemove', 'keydown', 'wheel', 'DOMMouseScroll', 'mousewheel', 'mousedown', 'touchstart', 'touchmove', 'MSPointerDown', 'MSPointerMove', 'visibilitychange', 'focus']`. - **immediateEvents** (array) - Optional - Events that trigger immediate action. Default: `[]`. - **debounce** (number) - Optional - Debounce time in milliseconds. Default: `0`. - **throttle** (number) - Optional - Throttle time in milliseconds. Default: `0`. - **eventsThrottle** (number) - Optional - Throttle time for events in milliseconds. Default: `200`. - **element** (HTMLElement) - Optional - Element to attach event listeners to. Default: `document`. - **startOnMount** (boolean) - Optional - Start the timer on mount. Default: `true`. - **startManually** (boolean) - Optional - Start the timer manually. Default: `false`. - **stopOnIdle** (boolean) - Optional - Stop the timer when idle. Default: `false`. - **crossTab** (boolean) - Optional - Enable cross-tab synchronization. Default: `false`. - **name** (string) - Optional - Name of the timer. Default: `'idle-timer'`. - **syncTimers** (number) - Optional - Synchronization interval in milliseconds. Default: `0`. - **leaderElection** (boolean) - Optional - Enable leader election. Default: `false`. ### Returns (IIdleTimer) - **start** (function) - Starts the timer. - **reset** (function) - Resets the timer. - **activate** (function) - Activates the timer. - **pause** (function) - Pauses the timer. - **resume** (function) - Resumes the timer. - **isIdle** (boolean) - Whether the user is idle. - **isPrompted** (boolean) - Whether the user is prompted. - **isLeader** (boolean) - Whether this tab is the leader. - **isLastActiveTab** (boolean) - Whether this tab is the last active tab. - **getTabId** (function) - Returns the tab ID. - **getRemainingTime** (function) - Returns the remaining time. - **getElapsedTime** (function) - Returns the elapsed time. - **getLastIdleTime** (function) - Returns the last idle time. - **getLastActiveTime** (function) - Returns the last active time. - **getIdleTime** (function) - Returns the idle time. - **getTotalIdleTime** (function) - Returns the total idle time. - **getActiveTime** (function) - Returns the active time. - **getTotalActiveTime** (function) - Returns the total active time. ``` -------------------------------- ### v5 crossTab with syncTimers (Hook and Component) Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx Shows the new syncTimers prop that takes a throttle value in milliseconds to keep timeouts across tabs roughly in sync. The example uses 200ms as a starting point. ```jsx // Hook const idleTimer = useIdleTimer({ crossTab: true, syncTimers: 200 }) // Higher Order Component Wrapped ``` -------------------------------- ### Prompt user before idle with promptBeforeIdle Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx Minimal example of integrated prompting using `promptBeforeIdle`, `onPrompt`, `onIdle`, `onActive`, and the `isPrompted()` and `getRemainingTime()` state getters. `onPrompt` fires `promptBeforeIdle` milliseconds before `timeout`; all events are disabled while the prompt is active. Call `activate()` to keep the user active, and note that `onActive` only fires if `activate()` is called while `isPrompted()` is true. ```jsx export function App () { // Set timeout values const timeout = 1000 * 60 * 30 const promptBeforeIdle = 1000 * 30 // Modal open state const [open, setOpen] = useState(false) // Time before idle const [remaining, setRemaining] = useState(0) const onPrompt = () => { // onPrompt will be called `promptBeforeIdle` milliseconds before `timeout`. // In this case 29 minutes and 30 seconds or 30 seconds before idle. // Here you can open your prompt. // All events are disabled while the prompt is active. // If the user wishes to stay active, call the `activate()` method. // You can get the remaining prompt time with the `getRemainingTime()` method, setOpen(true) setRemaining(promptTimeout) } const onIdle = () => { // onIdle will be called after the timeout is reached. // In this case 30 minutes. Here you can close your prompt and // perform whatever idle action you want such as logging out your user. // Events will be rebound as long as `stopOnMount` is not set. setOpen(false) setRemaining(0) } const onActive = () => { // onActive will only be called if `activate()` is called while `isPrompted()` // is true. Here you will also want to close your modal and perform // any active actions. 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 (

Logging you out in {remaining} seconds

) } ``` -------------------------------- ### Create IdleTimer wrapped component with withIdleTimer Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/with-idle-timer.mdx Create a wrapped component by extending IdleTimerComponent and using withIdleTimer. The IIdleTimer interface is supplied via props, and start() is called in componentDidMount. ```js import { withIdleTimer, IdleTimerComponent } from 'react-idle-timer' class AppComponent extends IdleTimerComponent { onPresenceChange (presence) { // Handle state changes in one function } onPrompt () { // Fire a Modal Prompt } onIdle () { // Close Modal Prompt // Do some idle action like logging out your user } onActive (event) { // Close Modal Prompt // Do some active action } onAction (event) { // Do something when a user triggers a watched event } componentDidMount () { // The IIdleTimer interface is supplied via props to your component this.props.start() } render () { return } } export const App = withIdleTimer(AppComponent) ``` -------------------------------- ### onPresenceChange type and example Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx Type definition and example implementation for the onPresenceChange event handler. The handler receives a PresenceType object and can be used in place of onActive, onIdle, and onPrompt. If both the generic handler and specific handlers are used, the generic handler is called first. ```ts // The presence type definition type PresenceType = { type: 'idle' } | { type: 'active', prompted: boolean } ``` ```ts // Example onPresenceChange implementation import type { PresenceType } from 'react-idle-timer' const onPresenceChange = (presence: PresenceType) => { const isIdle = presence.type === 'idle' const isActive = presence.type === 'active' && !presence.prompted const isPrompted = presence.type === 'active' && presence.prompted } ``` -------------------------------- ### Old way: manually start/pause timer with redux Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx Old way of controlling the idle timer based on a boolean value using start and pause methods. Requires useEffect and startManually: true. ```ts import { useEffect } from 'react' import { useSelector } from 'react-redux' import { useIdleTimer } from 'react-idle-timer' export const App = () => { const loggedIn = useSelector(state => state.user !== undefined) const { start, pause } = useIdleTimer({ startManually: true }) useEffect(() => { if (loggedIn) { start() } else { pause() } }, [ loggedIn ]) } ``` -------------------------------- ### Use IdleTimer component in App Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/with-idle-timer.mdx Use the IdleTimer component in a class component. It sets up event handlers and uses a ref to access the IIdleTimer interface, calling start() in componentDidMount. ```js import { Component } from 'react' import { IdleTimer } from './IdleTimer' export class App extends Component { constructor (props) { super(props) this.idleTimer = null this.onPresenceChange = this.onPresenceChange.bind(this) this.onPrompt = this.onPrompt.bind(this) this.onIdle = this.onIdle.bind(this) this.onAction = this.onAction.bind(this) this.onActive = this.onActive.bind(this) } onPresenceChange (presence) { // Handle state changes in one function } onPrompt () { // Fire a Modal Prompt } onIdle () { // Close Modal Prompt // Do some idle action like logging out your user } onActive (event) { // Close Modal Prompt // Do some active action } onAction (event) { // Do something when a user triggers a watched event } componentDidMount () { // IIdleTimer interface available on the reference to // the IdleTimer component instance this.idleTimer.start() } render () { return ( <> { this.idleTimer = ref }} timeout={1000 * 60 * 15} promptTimeout={1000 * 30} onPresenceChange={this.onPresenceChange} onPrompt={this.onPrompt} onIdle={this.onIdle} onAction={this.onAction} onActive={this.onActive} startManually /> ) } } ``` -------------------------------- ### Cross-tab messaging with Redux Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx Example using useIdleTimer with Redux to broadcast a logout action to all tabs. The onMessage handler dispatches a Redux action based on the received data, and the message emitter sends the action with emitOnSelf set to true to also trigger it in the current tab. ```jsx import { useIdleTimer } from 'react-idle-timer' import { useDispatch } from 'react-redux' import { logAction } from './Actions' export function App () { // Action dispatcher (redux) const dispatch = useDispatch() // Message handler const onMessage = data => { switch (data.action) { case 'LOGOUT_USER': dispatch(logoutAction()) break // More actions default: // no op } } // IdleTimer instance const { message } = useIdleTimer({ onMessage }) // Logout button click const onLogoutClick = () => { // Tell all tabs to log the user out. // Passing true as a second parameter will // also emit the event in this tab. message({ action: 'LOGOUT_USER' }, true) } return ( ) } ``` -------------------------------- ### TypeScript usage of withIdleTimer Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/with-idle-timer.mdx These two TypeScript examples show how to use the `withIdleTimer` higher-order component with generics. The first defines a component that extends `IdleTimerComponent` and uses the `IIdleTimer` interface for props, while the second renders that component elsewhere in the app, merging custom props with the idle timer props. ```tsx import { Component, ReactNode } from 'react' import { withIdleTimer, IdleTimerComponent, IIdleTimer } from 'react-idle-timer' interface IAppProps extends IIdleTimer { foo: string } interface IAppState { bar: string } class AppComponent extends IdleTimerComponent { onPresenceChange (presence) { // Handle state changes in one function } onPrompt (): void { // Fire a Modal Prompt } onIdle (): void { // Close Modal Prompt // Do some idle action like logging out your user } onActive (event: Event): void { // Close Modal Prompt // Do some active action } onAction (event: Event): void { // Do something when a user triggers a watched event } componentDidMount (): void { // The IIdleTimer interface is supplied via props to your component this.props.start() } render (): ReactNode { return (

{this.props.foo}

) } } export const IdleTimer = withIdleTimer(AppComponent) ``` ```tsx import { Component, ReactNode } from 'react' import { render } from 'react-dom' import { App } from './App' class Root extends Component<{}, {}> { render (): ReactNode { } } const element = document.getElementById('root') render(, element) ``` -------------------------------- ### New way: use disabled property with redux Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx New way of controlling the idle timer using the `disabled` property. When disabled, it stops the timer and disables control methods. Redux example. ```ts import { useSelector } from 'react-redux' import { useIdleTimer } from 'react-idle-timer' export const App = () => { const loggedIn = useSelector(state => state.user !== undefined) useIdleTimer({ disabled: !loggedIn }) } ``` -------------------------------- ### Environment variables for /docs .env.local Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/about/contributing.mdx Add this file to the /docs directory with a GitHub personal access token to work on the documentation locally. Replace [your_token] with your token. ```plaintext GOOGLE_ANALYTICS=G-XXXXXXXXXX GITHUB_TOKEN=[your_token] ``` -------------------------------- ### Mock MessageChannel for cross tab testing Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/testing.mdx Add this to your test.setup.js to mock the global MessageChannel, which is not mocked by default in js-dom. Required when using the cross tab feature. Includes cleanup after all tests. ```javascript import { MessageChannel } from 'worker_threads' import { cleanup } from '@testing-library/react' beforeAll(() => { // @ts-ignore global.MessageChannel = MessageChannel }) afterAll(cleanup) ``` -------------------------------- ### Mock timers with createMocks in test.setup.js Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/testing.mdx Add this to your test.setup.js to mock worker thread timers for testing. IdleTimer exposes the createMocks function to make the test runner use main thread timers. ```javascript import { createMocks } from 'react-idle-timer' beforeAll(createMocks) ``` -------------------------------- ### Import useIdleTimer from react-idle-timer/legacy Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/installation.mdx Import IdleTimer for legacy browser support in modern node.js runtimes. ```ts import { useIdleTimer } from 'react-idle-timer/legacy' ``` -------------------------------- ### Import useIdleTimer from 'react-idle-timer' Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/use-idle-timer.mdx Shows how to import the useIdleTimer hook from the react-idle-timer package. ```js import { useIdleTimer } from 'react-idle-timer' ``` -------------------------------- ### Leader election with isLeader method Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx Shows how to enable leader election manually and use the isLeader method inside the onIdle event handler to perform different actions depending on whether the current tab is the leader. ```js import { useIdleTimer } from 'react-idle-timer' const App = () => { const { isLeader } = useIdleTimer({ crossTab: true, leaderElection: true, onIdle: () => { if (isLeader()) { // I am the leader, perform remote action } else { // I am not the leader, perform local action } } }) return <> } ``` -------------------------------- ### Import useIdleTimer from legacy ESM path Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/installation.mdx Import IdleTimer for legacy browser support in ECMAScript Modules projects when node lacks package.json exports support. ```ts import { useIdleTimer } from 'react-idle-timer/dist/index.legacy.esm.js' ``` -------------------------------- ### Import IdleTimerProvider and related context exports Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/idle-timer-provider.mdx Import the IdleTimerProvider, IdleTimerConsumer, IIdleTimerContext, IdleTimerContext, and useIdleTimerContext from 'react-idle-timer'. ```ts import { IdleTimerProvider, IdleTimerConsumer, IIdleTimerContext, IdleTimerContext, useIdleTimerContext } from 'react-idle-timer' ``` -------------------------------- ### Configure idle timer with promptBeforeIdle Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx Use promptBeforeIdle instead of the deprecated promptTimeout. This sets a 30-minute idle timeout and triggers onPrompt 30 seconds before idle. Both properties work until v6.0.0. ```js const idleTimer = useIdleTimer({ timeout: 1000 * 60 * 30, promptBeforeIdle: 1000 * 30 }) ``` -------------------------------- ### Import useIdleTimer from legacy CommonJS path Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/installation.mdx Import IdleTimer for legacy browser support in CommonJS projects when node lacks package.json exports support. ```ts import { useIdleTimer } from 'react-idle-timer/dist/index.legacy.cjs.js' ``` -------------------------------- ### Import withIdleTimer Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/with-idle-timer.mdx Import the withIdleTimer higher-order component from the react-idle-timer package. ```js import { withIdleTimer } from 'react-idle-timer' ``` -------------------------------- ### Use wrapped IdleTimer component Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/with-idle-timer.mdx Render the wrapped App component with timeout, promptTimeout, and startManually props. ```js import { render } from 'react-dom' import { App } from './App' const element = document.getElementById('root') render(( ), element) ``` -------------------------------- ### immediateEvents configuration type Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx Type signature for the immediateEvents configuration option. Events listed here immediately switch the user to idle or prompted state, calling onIdle or onPrompt respectively, bypassing the timeout. If an event is in both events and immediateEvents, the immediate event takes precedence. ```ts immediateEvents?: IEventsType[] ``` -------------------------------- ### Enable web worker timers with workerTimers Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx Enables web worker timers by passing the `workerTimers` implementation to the `timers` property of `useIdleTimer`. Use this when you need accurate idle detection while the browser window is backgrounded and throttling main thread timers. Note that the worker is provided via a blob URL, which may violate strict CSP rules; update your CSP to allow it, or omit `timers` to use the default main thread timers. ```js import { useIdleTimer, workerTimers } from 'react-idle-timer' export const App = () => { const idleTimer = useIdleTimer({ timers: workerTimers }) return (

Using web worker timers!

) } ``` -------------------------------- ### isPrompted Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/methods.mdx Returns whether or not the prompt is active. ```APIDOC ## isPrompted() ### Description Returns whether or not the prompt is active. ### Method isPrompted ### Signature `() => boolean` ### Returns - **boolean** - `true` if the prompt is active, `false` otherwise. ``` -------------------------------- ### Use IIdleTimer callback parameters to handle prompts Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx Use the new callback parameters in v5.6.0 to access the IIdleTimer interface and control the timer during events. The onAction callback activates the timer if prompted, onActive closes the prompt, onPrompt opens it, and onIdle logs out. Configure with timeout and promptBeforeIdle. ```ts const onAction = (event: Event, idleTimer: IIdleTimer) => { if (idleTimer.isPrompted()) { idleTimer.activate() } } const onActive = (event: Event, idleTimer: IIdleTimer) => { if (idleTimer.isPrompted()) { setOpen(false) } } const onPrompt = () => { setOpen(true) } const onIdle = () => { setOpen(false) history.replace('/logout') } useIdleTimer({ timeout: 1000 * 60 * 5, promptBeforeIdle: 1000 * 30, onAction, onActive, onPrompt, onIdle }) ``` -------------------------------- ### IIdleTimerProps Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/types.mdx Import the IIdleTimerProps type from the react-idle-timer package. ```APIDOC ## Import IIdleTimerProps ### Description Import the `IIdleTimerProps` type from the `react-idle-timer` package to use in TypeScript projects. ### Import ```js import type { IIdleTimerProps } from 'react-idle-timer' ``` ``` -------------------------------- ### v4 crossTab configuration (Hook and Component) Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx Shows the v4 crossTab prop accepting an object of configuration options for both the useIdleTimer hook and the IdleTimer component. This is the old API that has been replaced in v5. ```jsx // Hook const idleTimer = useIdleTimer({ crossTab: { type: undefined, channelName: 'idle-timer', fallbackInterval: 2000, responseTime: 100, removeTimeout: 1000 * 60, emitOnAllTabs: true } }) // Component ``` -------------------------------- ### Create IdleTimer component extending IdleTimerComponent Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/with-idle-timer.mdx Create a custom IdleTimer component by extending IdleTimerComponent and wrapping it with withIdleTimer. This component renders its children. ```js import { Component } from 'react' import { withIdleTimer } from 'react-idle-timer' class IdleTimerComponent extends Component { render () { return this.props.children } } export const IdleTimer = withIdleTimer(IdleTimerComponent) ``` -------------------------------- ### IIdleTimer Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/types.mdx Import the IIdleTimer type from the react-idle-timer package. ```APIDOC ## Import IIdleTimer ### Description Import the `IIdleTimer` type from the `react-idle-timer` package to use in TypeScript projects. ### Import ```js import type { IIdleTimer } from 'react-idle-timer' ``` ``` -------------------------------- ### name Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/props.mdx Sets the name for the IdleTimer instance. Required when running multiple instances with crossTab enabled. ```APIDOC ## name ### Description Sets the name for the IdleTimer instance. This is required if you are running multiple instances with `crossTab` enabled. ### Type string ### Default Value idle-timer ``` -------------------------------- ### MessageType Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/types.mdx Import the MessageType type from the react-idle-timer package. ```APIDOC ## Import MessageType ### Description Import the `MessageType` type from the `react-idle-timer` package to use in TypeScript projects. ### Import ```js import type { MessageType } from 'react-idle-timer' ``` ``` -------------------------------- ### v5 simplified crossTab (Hook and Component) Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx Shows the new v5 crossTab prop that only accepts a boolean, for both the useIdleTimer hook and the IdleTimer component. This is the replacement for the v4 object configuration. ```jsx // Hook const idleTimer = useIdleTimer({ crossTab: true }) // Higher Order Component Wrapped ``` -------------------------------- ### leaderElection Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/props.mdx Enables the Leader Election feature, which assigns one tab as the leader. Use the isLeader method to determine if a tab is the leader. ```APIDOC ## leaderElection ### Description Enables the Leader Election feature. Leader Election will assign one tab to be the leader. To determine if a tab is the leader, use the `isLeader` method. ### Type boolean ### Default Value false ``` -------------------------------- ### getElapsedTime Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/methods.mdx Returns the number of milliseconds since the hook was mounted. ```APIDOC ## getElapsedTime() ### Description Returns the number of milliseconds since the hook was mounted. ### Method getElapsedTime ### Signature `() => number` ### Returns - **number** - The number of milliseconds since the hook was mounted. ``` -------------------------------- ### Use wrapped component deeper in hierarchy Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/with-idle-timer.mdx Instantiate the wrapped App component deeper in the component hierarchy, allowing dynamic supply and update of IIdleTimerProps via state. ```js import { Component } from 'react' import { App } from './App' export class Root extends Component { constructor (props) { super(props) this.state = { timeout: 1000 * 60 * 15, promptTimeout: 1000 * 30 } } render () { return ( ) } } ``` -------------------------------- ### getTotalElapsedTime Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/methods.mdx Returns the number of milliseconds since the hook last reset. ```APIDOC ## getTotalElapsedTime() ### Description Returns the number of milliseconds since the hook last reset. ### Method getTotalElapsedTime ### Signature `() => number` ### Returns - **number** - The number of milliseconds since the hook last reset. ``` -------------------------------- ### crossTab Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/props.mdx Enables cross tab event replication, allowing events to be replicated across browser tabs. ```APIDOC ## crossTab ### Description Enable cross tab event replication. ### Type boolean ### Default Value false ``` -------------------------------- ### getTotalActiveTime Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/methods.mdx Returns the total time in milliseconds user has been active since the component mounted. ```APIDOC ## getTotalActiveTime() ### Description Returns the total time in milliseconds user has been active since the component mounted. ### Method getTotalActiveTime ### Signature `() => number` ### Returns - **number** - The total active time in milliseconds since the component mounted. ``` -------------------------------- ### timers Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/props.mdx Sets custom timers. By default, main thread timers are used. To use worker thread timers, import them from the package and set them here. ```APIDOC ## timers ### Description Set custom timers. By default main thread timers are used to allow for better tree shaking. If you want to use worker thread timers, import them from the package and set them here. ### Type ITimers ### Default Value { setTimeout, clearTimeout, setInterval, clearInterval } ``` -------------------------------- ### getTotalIdleTime Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/methods.mdx Returns the total time in milliseconds user has been idle since the component mounted. ```APIDOC ## getTotalIdleTime() ### Description Returns the total time in milliseconds user has been idle since the component mounted. ### Method getTotalIdleTime ### Signature `() => number` ### Returns - **number** - The total idle time in milliseconds since the component mounted. ``` -------------------------------- ### isLeader Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/methods.mdx Returns whether or not the current tab is the leader. ```APIDOC ## isLeader() ### Description Returns whether or not the current tab is the leader. ### Method isLeader ### Signature `() => boolean` ### Returns - **boolean** - `true` if the current tab is the leader, `false` otherwise. ``` -------------------------------- ### Isolating crossTab events with name prop (Hook and Component) Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx Shows how to use the name prop to isolate crossTab events between multiple IdleTimer instances on the same page. Two timers are created with different names and timeouts. ```jsx // Hook 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' }) // Higher Order Component Wrapped ``` -------------------------------- ### Import EventsType type Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/types.mdx Imports the EventsType type, which contains all valid DOM Event values that can be passed to `events` and `immediateEvents`. ```typescript import type { EventsType } from 'react-idle-timer' ``` -------------------------------- ### Import ITimers type Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/types.mdx Imports the ITimers interface, which is accepted by the `timers` property. ```typescript import type { ITimers } from 'react-idle-timer' ``` -------------------------------- ### PresenceType Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/types.mdx Import the PresenceType type from the react-idle-timer package. ```APIDOC ## Import PresenceType ### Description Import the `PresenceType` type from the `react-idle-timer` package to use in TypeScript projects. ### Import ```js import type { PresenceType } from 'react-idle-timer' ``` ``` -------------------------------- ### Import IIdleTimer type Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/types.mdx Imports the IIdleTimer interface, which consists of the methods that can be called after instantiating an IdleTimer instance. ```typescript import type { IIdleTimer } from 'react-idle-timer' ``` -------------------------------- ### resume Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/methods.mdx Resumes an IdleTimer instance from the time it was paused. When resumed, all events will be bound. Returns a boolean denoting if the instance was resumed successfully. ```APIDOC ## resume() ### Description Resumes an IdleTimer instance from the time it was paused. When resumed, all events will be bound. Returns a boolean denoting if the instance was resumed successfully. ### Method resume ### Signature `() => boolean` ### Returns - **boolean** - `true` if the instance was resumed successfully, `false` otherwise. ``` -------------------------------- ### isIdle Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/methods.mdx Returns whether or not the user is idle. ```APIDOC ## isIdle() ### Description Returns whether or not the user is idle. ### Method isIdle ### Signature `() => boolean` ### Returns - **boolean** - `true` if the user is idle, `false` otherwise. ``` -------------------------------- ### getActiveTime Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/methods.mdx Returns the total time in milliseconds user has been active since the last reset. ```APIDOC ## getActiveTime() ### Description Returns the total time in milliseconds user has been active since the last reset. ### Method getActiveTime ### Signature `() => number` ### Returns - **number** - The total active time in milliseconds since the last reset. ``` -------------------------------- ### ITimers Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/types.mdx Import the ITimers type from the react-idle-timer package. ```APIDOC ## Import ITimers ### Description Import the `ITimers` type from the `react-idle-timer` package to use in TypeScript projects. ### Import ```js import type { ITimers } from 'react-idle-timer' ``` ``` -------------------------------- ### getIdleTime Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/methods.mdx Returns the total time in milliseconds user has been idle since the last reset. ```APIDOC ## getIdleTime() ### Description Returns the total time in milliseconds user has been idle since the last reset. ### Method getIdleTime ### Signature `() => number` ### Returns - **number** - The total idle time in milliseconds since the last reset. ``` -------------------------------- ### EventsType Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/types.mdx Import the EventsType type from the react-idle-timer package. ```APIDOC ## Import EventsType ### Description Import the `EventsType` type from the `react-idle-timer` package to use in TypeScript projects. ### Import ```js import type { EventsType } from 'react-idle-timer' ``` ``` -------------------------------- ### activate Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/methods.mdx Resets the IdleTimer instance to its initial state, restarting the timer, and emitting the `onActive` event if the user was idle or prompted. Returns a boolean denoting if the instance was activated successfully. ```APIDOC ## activate() ### Description Resets the IdleTimer instance to its initial state, restarting the timer, and emitting the `onActive` event if the user was idle or prompted. Returns a boolean denoting if the instance was activated successfully. ### Method activate ### Signature `() => boolean` ### Returns - **boolean** - `true` if the instance was activated successfully, `false` otherwise. ``` -------------------------------- ### Class component with contextType for IdleTimerContext Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/idle-timer-provider.mdx Set the contextType on a class component to consume the IdleTimer API outside of JSX, making it available on this.context. ```jsx import { Component } from 'react' import { IdleTimerContext, IdleTimerProvider } from 'react-idle-timer' export class Child extends Component { // Set the context type to the IdleTimerContext // The IIdleTimer interface will be available on this.context static contextType = IdleTimerContext render () { return (

{this.context.isIdle()}

) } } export class App extends Component { onPresenceChange (presence) { // Handle state changes in one function } onPrompt () { // Fire a Modal Prompt } onIdle () { // Close Modal Prompt // Do some idle action like log out your user } onActive (event) { // Close Modal Prompt // Do some active action } onAction (event) { // Do something when a user triggers a watched event } render () { return ( ) } } ``` -------------------------------- ### getTabId Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/methods.mdx Returns the current tabs id. ```APIDOC ## getTabId() ### Description Returns the current tabs id. ### Method getTabId ### Signature `() => string` ### Returns - **string** - The current tab's id. ``` -------------------------------- ### syncTimers Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/props.mdx Syncs timers across all tabs. The value is the duration of the throttle on the sync operation. Setting to 0 disables the feature. ```APIDOC ## syncTimers ### Description Syncs timers across all tabs. Timers are synced when user input is detected. The value of this property is the duration of the throttle on the sync operation. Setting to 0 disables the feature. ### Type number ### Default Value 0 ``` -------------------------------- ### Functional component usage with useIdleTimerContext Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/idle-timer-provider.mdx Use the IdleTimerProvider component and the useIdleTimerContext hook in functional components to access the IdleTimer API in child components. ```jsx import { IdleTimerProvider, useIdleTimerContext } from 'react-idle-timer' export function Child () { const idleTimer = useIdleTimerContext() return (

{idleTimer.isIdle()}

) } export function App () { const onPresenceChange = (presence) => { // Handle state changes in one function } const onPrompt = () => { // Fire a Modal Prompt } const onIdle = () => { // Close Modal Prompt // Do some idle action like log out your user } const onActive = (event) => { // Close Modal Prompt // Do some active action } const onAction = (event) => { // Do something when a user triggers a watched event } return ( ) } ``` -------------------------------- ### Import IIdleTimerProps type Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/types.mdx Imports the IIdleTimerProps interface, which defines the available properties that IdleTimer accepts. Use this type when working with IdleTimer's props in TypeScript projects. ```typescript import type { IIdleTimerProps } from 'react-idle-timer' ```