react-idle-timer

repository·master·Indexed 22 days ago

https://github.com/supremetechnopriest/react-idle-timer

Activity detection for React.js applications. This library monitors user interactions such as mouse movements, key presses, and clicks to trigger actions when a user becomes idle, enabling features like automatic session timeouts, inactivity warnings, and auto-logout.

Tokens
20.4K
Snippets
58
Records
92
Agent score
75%

What's inside react-idle-timer

  1. Overview of React Idle Timer

    master
    React Idle Timer is a library designed to detect user inactivity in React applications. It allows developers to monitor user interactions (like mouse movements, key presses, or clicks) and trigger specific actions when a user becomes idle for a defined period. This is commonly used for security features like auto-logout, session management, or displaying inactivity warnings.
  2. How idle detection works in react-idle-timer

    master
    Idle detection is the core feature of react-idle-timer. It tracks user activity by listening to specific DOM events (like mouse movements, key presses, or scrolls) on a target element. When the user fails to trigger these events within a specified timeout period, the library identifies the user as 'idle'. It can also track 'presence' (the transition between active and idle states) and provide callbacks when these states change.
  3. Configure Cross Tab functionality in v5

    master

    The Cross Tab API has been simplified in v5. The crossTab prop now accepts a boolean to enable or disable the feature. Most configuration options from v4 are now set to sane defaults.

    Syncing Timers

    Use the syncTimers property (a number representing milliseconds) to replicate user actions across all tabs, keeping timeouts in sync. A value of 200 is a recommended starting point to balance synchronization with messaging overhead.

    Isolating Instances

    If using multiple IdleTimer instances on the same page, use the name prop to ensure cross-tab events are isolated to their respective instances.

    // Hook with Cross Tab and Syncing enabled
    const idleTimer = useIdleTimer({
      crossTab: true,
      syncTimers: 200
    })
    
    // Multiple isolated instances
    const logoutTimer = useIdleTimer({
      timeout: 1000 * 60 * 30,
      crossTab: true,
      syncTimers: 200,
      name: 'logout-timer'
    })
    
    const activityTimer = useIdleTimer({
      timeout: 1000 * 60 * 5,
      crossTab: true,
      syncTimers: 200,
      name: 'activity-timer'
    })
  4. Implement Integrated Prompting

    master

    You can automatically prompt a user before they go idle (e.g., showing a modal to ask if they are still there).

    Key properties and methods:

    • promptBeforeIdle: The amount of time (in ms) before the timeout is reached that the prompt should trigger.
    • onPrompt(): Event handler called when the prompt state is entered. All other events are disabled while the prompt is active.
    • onIdle(): Event handler called when the full timeout is reached.
    • onActive(): Event handler called if the user interacts/activates while in the prompted state.
    • isPrompted(): State getter to check if the user is currently in the prompted state.
    • getRemainingTime(): Returns the remaining time until the idle state is reached.
    • activate(): Manually resets the timer and triggers onActive if the user was idle or prompted.
    export function App () {
      const timeout = 1000 * 60 * 30
      const promptBeforeIdle = 1000 * 30
      const [open, setOpen] = useState(false)
      const [remaining, setRemaining] = useState(0)
    
      const onPrompt = () => {
        setOpen(true)
        setRemaining(promptTimeout)
      }
    
      const onIdle = () => {
        setOpen(false)
        setRemaining(0)
      }
    
      const onActive = () => {
        setOpen(false)
        setRemaining(0)
      }
    
      const { getRemainingTime, isPrompted, activate } = useIdleTimer({
        timeout,
        promptBeforeIdle,
        onPrompt,
        onIdle,
        onActive
      })
    
      const handleStillHere = () => {
        setOpen(false)
        activate()
      }
    
      useEffect(() => {
        const interval = setInterval(() => {
          if (isPrompted()) {
            setRemaining(Math.ceil(getRemainingTime() / 1000))
          }
        }, 1000)
        return () => clearInterval(interval)
      }, [getRemainingTime, isPrompted])
    
      return (
        <div className='modal' style={{ display: open ? 'block': 'none' }}>
          <p>Logging you out in {remaining} seconds</p>
          <button onClick={handleStillHere}>Im Still Here</button>
        </div>
      )
    }
  5. Use IdleTimerProvider to avoid prop drilling

    master

    Instead of passing the IdleTimer API through multiple layers of your component tree (prop drilling), use the IdleTimerProvider to make the API available to all descendant components via React Context. This allows any child component to access idle state and methods directly.

    import { IdleTimerProvider } from 'react-idle-timer'
    
    function App() {
      return (
        <IdleTimerProvider timeout={1000 * 60}>
          <Child />
        </IdleTimerProvider>
      )
    }
  6. Follow Git commit message guidelines

    master

    IdleTimer enforces strict commit message guidelines. Messages must use the present tense and imperative mood (e.g., "Add feature" instead of "Added feature"), and the first line must be 72 characters or less.

    Every commit must start with an applicable emoji to categorize the change:

    EmojiTokenPurpose
    :art::art:Improving code format/structure
    :stopwatch::stopwatch:Improving performance
    :memo::memo:Writing documentation
    :zap::zap:Adding a new feature
    :sparkles::sparkles:Enhancing an existing feature
    :lady_beetle::lady_beetle:Fixing a bug
    :fire::fire:Removing code or files
    :green_heart::green_heart:Fixing the CI build
    :white_check_mark::white_check_mark:Adding tests
    :lock::lock:Dealing with security
    :arrow_up::arrow_up:Upgrading dependencies
    :arrow_down::arrow_down:Downgrading dependencies
    :shirt::shirt:Removing linter warnings
    :shower::shower:Generic cleanup
  7. Enable and configure the Cross Tab feature

    master

    The Cross Tab feature allows you to reconcile events and state across multiple browser tabs running your application. It provides a messaging layer to broadcast messages to all tabs and includes features like leader election and timer synchronization.

    To use this feature, you must enable the crossTab property in your configuration. If you are running multiple idle timer instances on the same page, you must provide a unique name for each instance to avoid collisions.

    // Example configuration concept
    <IdleTimer
      crossTab={true}
      name="my-unique-timer-name"
      syncTimers={true}
      leaderElection={true}
    />
  8. Use the withIdleTimer Higher Order Component

    master

    The withIdleTimer Higher Order Component (HOC) is designed for class-based React applications. It accepts IIdleTimerProps as configuration and injects the IIdleTimer interface into the wrapped component. You can use it in two primary ways: as a standalone component or as an injector for your existing components.

    import { withIdleTimer } from 'react-idle-timer'
  9. Submit a Pull Request

    master

    Once your changes are complete, follow these steps to submit a Pull Request (PR):

    1. Fill out the "Ready for review" template to explain your changes.
    2. Link the PR to an issue if you are solving a specific task.
    3. Enable the checkbox to "allow maintainer edits" so the branch can be updated for merging.
    4. Respond to reviews: Address comments or suggested changes. Mark conversations as resolved once they are addressed.
    5. Resolve conflicts: If merge issues arise, you may need to resolve conflicts manually.