useIdle Hook
Introduction
A custom React Hook for detecting user idle state.
Play
Introduction
A custom React Hook for detecting user idle state.
Usage
import { useRef } from "react";
import { useIdle } from "@cannonui/reacthooks";
const TestUseIdle = () => {
const element = useRef<HTMLDivElement>(null);
const isIdle = useIdle(2000);
return (
<div>
<div
style={{ width: "100px", height: "100px", background: "cyan" }}
ref={element}
>
splace mouse here and do not move
</div>
<div>is idle: {isIdle ? "true" : "false"}</div>
</div>
);
};
export default TestUseIdle;
Return Value
The hook returns a boolean value indicating whether the user is idle or not.
Parameters
Name | Type | Description |
---|---|---|
interval | number | The interval (in milliseconds) to detect user idle. |
Features
- Detects user idle state based on specified idle interval.
- Returns a boolean value indicating whether the user is idle or not.
Example
In this example, we have a component called TestUseIdle
that uses the useIdle
hook to detect whether the user is idle or not. The hook listens for mouse movements, keyboard events, scrolling, and touch events. If no activity is detected within the specified interval (2000 milliseconds), the isIdle
state will be set to true
.
Use Scenario
The useIdle
hook is useful in scenarios where you want to detect user inactivity and trigger certain actions when the user becomes idle. For example, you might want to show a notification or perform an auto-logout after a certain period of user inactivity. By using the useIdle
hook, you can easily track user idle state and implement various idle-related features in your application.