### Local Project Setup Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/about/contributing.mdx Steps to set up the react-idle-timer project locally for development. This includes forking the repository, installing Node.js and dependencies, and setting up environment variables. ```bash npm install npm install -g nps ``` -------------------------------- ### Local Project Setup Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/CONTRIBUTING.md Steps to set up the react-idle-timer project locally for development. This includes forking the repository, installing Node.js and dependencies, and setting up environment variables. ```bash npm install npm install -g nps ``` -------------------------------- ### Install with npm Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/installation.mdx Installs the react-idle-timer package using npm. This is the standard way to add the library to your project. ```bash npm i react-idle-timer ``` -------------------------------- ### Install with yarn Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/installation.mdx Installs the react-idle-timer package using yarn. This is an alternative package manager for adding the library to your project. ```bash yarn add react-idle-timer ``` -------------------------------- ### Full Mock Setup for IdleTimer Testing Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/testing.mdx Combines the necessary mocks for both timers and MessageChannel into a single setup file for comprehensive testing of React Idle Timer. This includes Jest configuration to point to the setup file. ```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) ``` -------------------------------- ### Environment Configuration Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/CONTRIBUTING.md Example of a local environment file (`.env.local`) required for documentation development, including placeholders for Google Analytics and GitHub Personal Access Token. ```env GOOGLE_ANALYTICS=G-XXXXXXXXXX GITHUB_TOKEN=[your_token] ``` -------------------------------- ### onPresenceChange Implementation Example Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx An example implementation of the `onPresenceChange` event handler, showing how to process different presence states (idle, active, prompted) and react accordingly. This handler can consolidate logic previously handled by `onActive`, `onIdle`, and `onPrompt`. ```ts 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 // Handle state changes here } ``` -------------------------------- ### Environment Configuration Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/about/contributing.mdx Example of a local environment file (`.env.local`) required for documentation development, including placeholders for Google Analytics and GitHub Personal Access Token. ```env GOOGLE_ANALYTICS=G-XXXXXXXXXX GITHUB_TOKEN=[your_token] ``` -------------------------------- ### Legacy Browser Support (TypeScript) Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/installation.mdx Imports the legacy version of IdleTimer for use in modern Node.js runtimes with TypeScript. This ensures compatibility with older environments. ```typescript import { useIdleTimer } from 'react-idle-timer/legacy' ``` -------------------------------- ### Mock Timers for Testing Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/testing.mdx Mocks the main thread timers for testing environments, ensuring IdleTimer functions correctly when using worker threads. This setup is typically placed in a test setup file. ```javascript import { createMocks } from 'react-idle-timer' beforeAll(createMocks) ``` -------------------------------- ### Legacy Browser Support (CommonJS) Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/installation.mdx Imports the legacy version of IdleTimer for CommonJS module systems. This is necessary for older Node.js versions lacking support for package.json exports. ```typescript import { useIdleTimer } from 'react-idle-timer/dist/index.legacy.cjs.js' ``` -------------------------------- ### Legacy Browser Support (ECMAScript Modules) Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/installation.mdx Imports the legacy version of IdleTimer for ECMAScript Module systems. This is required for older Node.js versions lacking support for package.json exports. ```typescript import { useIdleTimer } from 'react-idle-timer/dist/index.legacy.esm.js' ``` -------------------------------- ### Minimal useIdleTimer Usage Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/use-idle-timer.mdx A basic example of using the useIdleTimer hook in a functional React component with essential configuration, focusing on the onPresenceChange callback. ```js import { useIdleTimer } from 'react-idle-timer' export const App = () => { const onPresenceChange = (presence) => { // Handle state changes in one function } const idleTimer = useIdleTimer({ onPresenceChange }) return ( ) } ``` -------------------------------- ### Full useIdleTimer Configuration and Methods Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/use-idle-timer.mdx An extensive example showcasing the useIdleTimer hook with all available props and methods. It includes various event handlers like onPrompt, onIdle, onActive, onAction, and detailed configuration for timeouts, events, and cross-tab synchronization. ```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 ( ) } ``` -------------------------------- ### Cross Tab Messaging Example Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx Demonstrates how to use the `message` emitter and `onMessage` callback to broadcast messages between different tabs of a React application using react-idle-timer. This allows for synchronized actions across multiple instances. ```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 ( ) } ``` -------------------------------- ### Use IdleTimer with Functional Components via Hook Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/idle-timer-provider.mdx Demonstrates using the `useIdleTimerContext` hook within functional components to access the IdleTimer API. Includes an example of setting up the `IdleTimerProvider` with various event handlers like onPresenceChange, onPrompt, onIdle, onActive, and onAction. ```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 ( ) ``` -------------------------------- ### Rendering react-idle-timer Component with Custom Props Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/with-idle-timer.mdx Shows how to render a custom component integrated with react-idle-timer. This example illustrates passing custom props like `foo` and specific timeout configurations (`timeout`, `promptTimeout`) to the component. ```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) ``` -------------------------------- ### TypeScript HOC Usage with react-idle-timer Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/with-idle-timer.mdx Demonstrates using `withIdleTimer` generics to preserve TypeScript types. It shows how to define custom props extending `IIdleTimer`, implement various event handlers, and start the timer via props. Custom props are merged with the `IIdleTimer` interface. ```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) ``` -------------------------------- ### Contribution Scripts Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/CONTRIBUTING.md Key scripts available via `package-scripts.js` for contributors, focusing on testing source code and developing documentation. ```bash nps.test nps docs.dev ``` -------------------------------- ### Contribution Scripts Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/about/contributing.mdx Key scripts available via `package-scripts.js` for contributors, focusing on testing source code and developing documentation. ```bash nps.test nps docs.dev ``` -------------------------------- ### Legacy Bundle Support Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx Introduced in v5.7.0, a legacy bundle is now included to provide support for older browsers that may not be compatible with the main package. ```ts import { useIdleTimer } from 'react-idle-timer/legacy' ``` -------------------------------- ### Activity Detection API Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/features/activity-detection.mdx Documentation for the properties and methods related to the activity detection feature, including event listeners, callbacks, and lifecycle management. ```APIDOC Activity Detection Properties: events: Array | string Description: The events to listen for activity on. Can be an array of event names (e.g., ['click', 'mousemove']) or a single event name. Type: Array | string Default: ['mousemove', 'keydown', 'touchstart'] element: HTMLElement | null Description: The DOM element to bind event listeners to. If not provided, listeners are bound to the document. Type: HTMLElement | null Default: null onAction: ((event: Event) => void) | null Description: Function called each time an event is triggered. Receives the triggering event object as an argument. Type: ((event: Event) => void) | null Default: null throttle: number Description: Throttle the `onAction` callback in milliseconds. Prevents the callback from being called more often than specified. Type: number Default: 0 debounce: number Description: Debounce the `onAction` callback in milliseconds. Delays the execution of the callback until a specified time has passed without any activity. Type: number Default: 0 startOnMount: boolean Description: Bind the events when the host component mounts. If true, activity detection starts automatically. Type: boolean Default: true startManually: boolean Description: Require a call to `start()` in order to bind the events initially. If true, activity detection will not start until the `start()` method is explicitly called. Type: boolean Default: false Activity Detection Methods: start(): void Description: Binds the events to the specified element or document, initiating activity detection. Usage: Call this method to begin tracking user activity. pause(): void Description: Unbinds the events, effectively pausing activity detection. Usage: Call this method to temporarily stop tracking user activity. resume(): void Description: Rebinds the events, resuming activity detection if it was paused. Usage: Call this method to restart tracking user activity after pausing. getElapsedTime(): number Description: Returns the amount of milliseconds since the host component was mounted or the activity detection was last reset. Returns: The elapsed time in milliseconds. Type: number ``` -------------------------------- ### Git Commit Message Guidelines Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/CONTRIBUTING.md Guidelines for writing effective Git commit messages, including tense, mood, length limits, referencing issues, and using specific emojis to categorize changes. ```git Use the present tense ("Add feature" not "Added feature") Use the imperative mood ("Move cursor to..." not "Moves cursor to...") Limit the first line to 72 characters or less Reference issues and pull requests liberally after the first line Start the commit message with an applicable emoji: :art: When improving the format/structure of the code. :stopwatch: When improving performance. :memo: When writing docs. :zap: When adding a new feature. :sparkles: When enhancing an existing feature. :lady_beetle: When fixing a bug. :fire: When removing code or files. :green_heart: When fixing the CI build. :white_check_mark: When adding tests. :lock: When dealing with security. :arrow_up: When upgrading dependencies. :arrow_down: When downgrading dependencies. :shirt: When removing linter warnings. :shower: When performing generic clean up. ``` -------------------------------- ### useIdleTimer Hook - `disabled` Property Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx The `disabled` property simplifies controlling the timer's active state. When set to true, the timer is paused, and its control methods (`start`, `reset`, `activate`, `pause`, `resume`, `message`) are disabled, returning false to indicate they were ignored. This reduces boilerplate code for common conditional logic. ```ts useIdleTimer({ disabled: !loggedIn }) // When disabled: // start(), pause(), reset(), activate(), resume(), message() return false. ``` ```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) // Old way: // const { start, pause } = useIdleTimer({ startManually: true }) // useEffect(() => { // if (loggedIn) { // start() // } else { // pause() // } // }, [ loggedIn ]) // New way: useIdleTimer({ disabled: !loggedIn }) } ``` -------------------------------- ### Git Commit Message Guidelines Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/about/contributing.mdx Guidelines for writing effective Git commit messages, including tense, mood, length limits, referencing issues, and using specific emojis to categorize changes. ```git Use the present tense ("Add feature" not "Added feature") Use the imperative mood ("Move cursor to..." not "Moves cursor to...") Limit the first line to 72 characters or less Reference issues and pull requests liberally after the first line Start the commit message with an applicable emoji: :art: When improving the format/structure of the code. :stopwatch: When improving performance. :memo: When writing docs. :zap: When adding a new feature. :sparkles: When enhancing an existing feature. :lady_beetle: When fixing a bug. :fire: When removing code or files. :green_heart: When fixing the CI build. :white_check_mark: When adding tests. :lock: When dealing with security. :arrow_up: When upgrading dependencies. :arrow_down: When downgrading dependencies. :shirt: When removing linter warnings. :shower: When performing generic clean up. ``` -------------------------------- ### IdleTimer Instance Methods Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/methods.mdx Provides access to the core functionalities of the IdleTimer instance, allowing control over its state and retrieval of timing information. ```APIDOC start() - Resets the IdleTimer instance to its initial state and starts the timer. - Returns: A boolean denoting if the instance was started successfully. reset() - Resets the IdleTimer instance to its initial state. - Returns: A boolean denoting if the instance was reset successfully. activate() - 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. pause() - Pauses the IdleTimer instance. When paused all events are unbound. - Returns: A boolean denoting if the instance was paused successfully. resume() - 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. message(data: MessageType, emitOnSelf?: boolean) - Broadcast an arbitrary message to all instances of IdleTimer. If crossTab is enabled, all tabs will receive the message and their `onMessage` callback will be emitted. If `emitOnSelf` is set to true, the callee instance will also emit its `onMessage` callback. - Parameters: - data: MessageType - The message payload to broadcast. - emitOnSelf?: boolean - Whether to emit the message on the calling instance as well. - Returns: A boolean denoting if the message was sent successfully. isIdle() - Returns whether or not the user is idle. - Returns: boolean isPrompted() - Returns whether or not the prompt is active. - Returns: boolean isLeader() - Returns whether or not the current tab is the leader. - Returns: boolean isLastActiveTab() - Returns whether or not the current tab is the last active tab. - Returns: boolean getTabId() - Returns the current tabs id. - Returns: string getRemainingTime() - Returns the number of milliseconds until idle. - Returns: number getElapsedTime() - Returns the number of milliseconds since the hook was mounted. - Returns: number getTotalElapsedTime() - Returns the number of milliseconds since the hook last reset. - Returns: number getLastIdleTime() - Returns the last time the user was idle. Returns a Date instance that can be formatted. - Returns: Date | null getLastActiveTime() - Returns the last time the user was active. Returns a Date instance that can be formatted. - Returns: Date | null getIdleTime() - Returns the total time in milliseconds user has been idle since the last reset. - Returns: number getTotalIdleTime() - Returns the total time in milliseconds user has been idle since the component mounted. - Returns: number getActiveTime() - Returns the total time in milliseconds user has been active since the last reset. - Returns: number getTotalActiveTime() - Returns the total time in milliseconds user has been active since the component mounted. - Returns: number ``` -------------------------------- ### Import IdleTimer Components and Hooks Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/idle-timer-provider.mdx Imports essential components and hooks from the 'react-idle-timer' library, including the Provider, Consumer, context interfaces, and the useIdleTimerContext hook. ```ts import { IdleTimerProvider, IdleTimerConsumer, IIdleTimerContext, IdleTimerContext, useIdleTimerContext } from 'react-idle-timer' ``` -------------------------------- ### useIdleTimer Hook - Callback Parameters Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx In v5.6.0, all callback functions (`onAction`, `onActive`, `onIdle`, `onPrompt`, etc.) now receive the `IIdleTimer` interface as their second parameter. This allows direct access to the timer's API and state within the callback functions, eliminating the need for hoisting or external state management for timer interactions. ```ts const onAction = (event: Event, idleTimer: IIdleTimer) => { if (idleTimer.isPrompted()) { idleTimer.activate() } } const onActive = (event: Event, idleTimer: IIdleTimer) => { if (idleTimer.isPrompted()) { setOpen(false) } } useIdleTimer({ timeout: 1000 * 60 * 5, promptBeforeIdle: 1000 * 30, onAction, onActive, onPrompt: () => setOpen(true), onIdle: () => { setOpen(false) history.replace('/logout') } }) ``` -------------------------------- ### IdleTimer Instance Methods Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/features/idle-detection.mdx Provides methods to control and query the state of the IdleTimer instance. These methods allow programmatic management of the timer's lifecycle and retrieval of activity-related timestamps and durations. ```APIDOC IdleTimer Methods: - start(): Starts or resumes the timer. If the timer was paused or stopped on idle, this will restart it. - reset(): Resets the timer to its initial state. Clears any pending idle/active states and restarts the timer if it was running. - activate(): Resets the IdleTimer instance to its initial state, starts the timer, and emits `onActive` if the user was previously idle. This is a comprehensive reset and activation. - pause(): Pauses a running timer. The timer will not track activity or trigger idle states until `resume()` or `start()` is called. - resume(): Resumes a paused timer. The timer will resume tracking activity from where it left off. - getElapsedTime(): Returns the total time in milliseconds since the host component was mounted. - getRemainingTime(): Returns the time remaining in milliseconds until the user is considered idle. Returns 0 if already idle or if the timer is not running. - getLastActiveTime(): Returns a Date object representing the last time the user was active. - getActiveTime(): Returns the total time in milliseconds the user has been active since the last reset. - getTotalActiveTime(): Returns the total time in milliseconds the user has been active since the component mounted. - getLastIdleTime(): Returns a Date object representing the last time the user was idle. - getIdleTime(): Returns the total time in milliseconds the user has been idle since the last reset. - getTotalIdleTime(): Returns the total time in milliseconds the user has been idle since the component mounted. ``` -------------------------------- ### Integrated Prompting with react-idle-timer Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx Implement a prompt to ask users if they are still active before the idle timeout is reached. This involves the `promptBeforeIdle` prop and the `onPrompt`, `onIdle`, and `onActive` event handlers. The `isPrompted()` state getter and `activate()` method are crucial for managing the prompt state and user interaction. ```jsx import React, { useState, useEffect } from 'react' import { useIdleTimer } from 'react-idle-timer' export function App () { // Set timeout values const timeout = 1000 * 60 * 30 // 30 minutes const promptBeforeIdle = 1000 * 30 // 30 seconds before idle // 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`. // Here you can open your prompt. // All events are disabled while the prompt is active. setOpen(true) setRemaining(promptBeforeIdle / 1000) // Set initial remaining time } const onIdle = () => { // onIdle will be called after the timeout is reached. // Here you can close your prompt and perform whatever idle action you want. 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() // Reactivate the timer and dismiss the prompt } useEffect(() => { const interval = setInterval(() => { if (isPrompted()) { setRemaining(Math.ceil(getRemainingTime() / 1000)) } }, 1000) return () => { clearInterval(interval) } }, [getRemainingTime, isPrompted]) return (

Logging you out in {remaining} seconds

Idle Timer Example

) } ``` -------------------------------- ### Render Wrapped IdleTimer Component Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/with-idle-timer.mdx Renders the `App` component (which has been wrapped with `withIdleTimer`), passing configuration props directly to it. ```jsx import { render } from 'react-dom' import { App } from './App' const element = document.getElementById('root') render ( ), element) ``` -------------------------------- ### Import withIdleTimer HOC Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/with-idle-timer.mdx Imports the `withIdleTimer` higher-order component from the react-idle-timer library. ```javascript import { withIdleTimer } from 'react-idle-timer' ``` -------------------------------- ### Mock MessageChannel for Cross-Tab Testing Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/testing.mdx Mocks the global MessageChannel, which is used internally by IdleTimer for cross-tab communication. This is necessary because js-dom does not mock it by default. Includes cleanup for testing libraries. ```javascript import { MessageChannel } from 'worker_threads' import { cleanup } from '@testing-library/react' beforeAll(() => { // @ts-ignore global.MessageChannel = MessageChannel }) afterAll(cleanup) ``` -------------------------------- ### Robots.txt Configuration Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/public/robots.txt Standard robots.txt file configuration to control web crawler access. This snippet specifies that all user agents are allowed to crawl any path. ```robots.txt User-agent: * Disallow: ``` -------------------------------- ### Import useIdleTimer Hook Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/use-idle-timer.mdx Demonstrates how to import the useIdleTimer hook from the 'react-idle-timer' library into a JavaScript or TypeScript React component. ```js import { useIdleTimer } from 'react-idle-timer' ``` -------------------------------- ### Migration: Removal of `` Component Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx A significant breaking change in v5 is the removal of the standalone `` component. It has been replaced by the `withIdleTimer` higher-order component (HOC). The HOC can be used to recreate the `IdleTimer` component functionality, serving as a drop-in replacement for v4 users. ```APIDOC Component Migration: - Removed: `` component. - Replaced by: `withIdleTimer` higher-order component. - Usage: Use `withIdleTimer` to create a component with the same behavior as the v4 ``. ``` -------------------------------- ### Use Custom IdleTimer Component Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/with-idle-timer.mdx Renders the `IdleTimer` component, passing event handlers and configuration props like `timeout` and `promptTimeout`. The `ref` is used to access the IdleTimer instance methods. ```jsx 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 /> ) } } ``` -------------------------------- ### useIdleTimer Hook - `promptTimeout` Deprecation Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx The `promptTimeout` property has been deprecated in favor of `promptBeforeIdle`. While `promptTimeout` will continue to function until v6.0.0, it is recommended to use `promptBeforeIdle` for clearer intent. `timeout` defines the total time until idle, and `promptBeforeIdle` defines the duration before idle to trigger the `onPrompt` event. ```js const idleTimer = useIdleTimer({ timeout: 1000 * 60 * 30, // 30 minutes until idle promptBeforeIdle: 1000 * 30 // 30 seconds before idle to prompt }) ``` -------------------------------- ### Create Custom IdleTimer Component Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/api/with-idle-timer.mdx Defines a custom `IdleTimerComponent` that extends `IdleTimerComponent` and wraps it with `withIdleTimer` to create a reusable IdleTimer component. ```javascript import { Component } from 'react' import { withIdleTimer } from 'react-idle-timer' class IdleTimerComponent extends Component { render () { return this.props.children } } export const IdleTimer = withIdleTimer(IdleTimerComponent) ``` -------------------------------- ### Update crossTab Prop from v4 to v5 Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx Illustrates the simplification of the `crossTab` prop in react-idle-timer v5. The complex object configuration from v4 is replaced by a simple boolean, with advanced options now handled by defaults or new props like `syncTimers`. ```jsx // v4 Example (Hook) const idleTimerV4Hook = useIdleTimer({ crossTab: { type: undefined, channelName: 'idle-timer', fallbackInterval: 2000, responseTime: 100, removeTimeout: 1000 * 60, emitOnAllTabs: true } }) // v4 Example (Component) // v5 Example (Hook) const idleTimerV5Hook = useIdleTimer({ crossTab: true }) // v5 Example (Higher Order Component Wrapped) ``` -------------------------------- ### Web Worker Timers with react-idle-timer Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx Utilize web worker timers to maintain accurate idle detection even when the browser throttles background tabs. This requires passing the `workerTimers` implementation to the `useIdleTimer` hook. Be aware of potential CSP violations and adjust rules accordingly. ```javascript import { useIdleTimer, workerTimers } from 'react-idle-timer' export const App = () => { const idleTimer = useIdleTimer({ timers: workerTimers }) return (

Using web worker timers!

) } ``` -------------------------------- ### Implement syncTimers for Cross Tab Synchronization Source: https://github.com/supremetechnopriest/react-idle-timer/blob/master/docs/pages/docs/getting-started/new.mdx Demonstrates the usage of the new `syncTimers` prop in react-idle-timer v5. This prop controls the throttle interval in milliseconds for synchronizing user actions across tabs, ensuring timeouts remain roughly in sync. ```jsx // Hook Usage const idleTimerSyncHook = useIdleTimer({ crossTab: true, syncTimers: 200 }) // Component Usage ```