-
Notifications
You must be signed in to change notification settings - Fork 0
useIdle
A highly optimized hook that detects user inactivity across the entire browser window. Perfect for auto-logout mechanisms, pausing heavy animations, or showing "Are you still there?" prompts.
Detecting if the user hasn't moved their mouse or pressed a key for 60 seconds (the default).
import { useIdle } from "react-hook-lab";
function StatusIndicator() {
const isIdle = useIdle(); // Defaults to 60000ms (1 minute)
return (
<div>
<p>Status: {isIdle ? "Away" : "Active"}</p>
</div>
);
}Setting a custom inactivity threshold, like 5 minutes.
import { useIdle } from "react-hook-lab";
function AutoLogout() {
// 5 minutes in milliseconds
const isIdle = useIdle(5 * 60 * 1000);
if (isIdle) {
return (
<div className="modal">
<h2>You've been inactive for 5 minutes!</h2>
<button>Keep Session Alive</button>
</div>
);
}
return null;
}Customizing the exact DOM events that count as "activity".
import { useIdle } from "react-hook-lab";
function CustomIdle() {
// Only counts mouse clicks or screen taps as activity.
// Moving the mouse without clicking will NOT reset the idle timer!
const isIdle = useIdle(30000, ["mousedown", "touchstart"]);
return <p>{isIdle ? "No clicks detected!" : "User is clicking around."}</p>;
}-
timeout(Optional)- Type:
number - Default:
60000(60 seconds) - Description: The duration in milliseconds of inactivity required before the user is considered idle.
- Type:
-
events(Optional)- Type:
(keyof WindowEventMap)[] - Default:
["mousemove", "mousedown", "keydown", "touchstart", "scroll", "wheel"] - Description: An array of native DOM events to listen to for activity.
- Type:
Returns a boolean:
-
true: The user has been inactive longer than thetimeout. -
false: The user is active or the timeout hasn't elapsed.
When mounted, useIdle attaches passive event listeners to the global window object for the specified events.
Whenever any of these events fire, a resetTimer function is called.
Performance Optimized: Binding a state-setter to a mousemove event would normally cause catastrophic performance degradation by triggering thousands of re-renders per second. useIdle solves this by applying a hardcoded 500ms throttle. If a user moves their mouse rapidly for 10 seconds, the reset function only executes roughly 20 times (instead of 600 times), perfectly preserving your app's framerate while keeping the idle timer perfectly accurate.
Built with ❤️ by Saurav-TB-Pandey. | Report an Issue | NPM