@toluade/use-window-inactivity
v0.1.0
Published
A React hook that returns the inactivity state of a window.
Maintainers
Readme
useWindowInactivity
A React hook that returns the inactivity state of a window.
Install
npm
npm i @toluade/use-window-inactivity --saveyarn
yarn add @toluade/use-window-inactivityReact 18 or 19 is required. React is a peer dependency, so the hook runs on the copy of React already in your app.
Example Usage
import useWindowInactivity from "@toluade/use-window-inactivity";
function App() {
const inactive = useWindowInactivity(5);
return (
<div>{inactive ? <p>Window is inactive</p> : <p>Window is active</p>}</div>
);
}API
const inactive = useWindowInactivity(5);Props
delay: number- This is the amount of time (in seconds) it takes to return a positive inactive state.
- Default value is
5seconds.
Returns
inactive: boolean- Returns
truewhen the window is inactive after the number of seconds passed to theuseWindowInactivityhook. - Returns
falsewhen window is active.
- Returns
What counts as activity
mousemove, mousedown, keydown, wheel, scroll, touchstart and
touchmove. Any one of them resets the countdown.
These are observed on window during the capture phase, which means scrolling
inside a nested element still counts as activity — scroll events do not bubble
— and a stopPropagation() in your own handlers cannot hide activity from the
hook.
Behaviour
- The countdown starts on mount, so a window that never sees an activity event
is reported inactive once
delayhas passed. - Changing
delayrestarts the countdown with the new value. It does not reset an already inactive state, since changing a prop is not user activity. - The listeners and any pending timer are removed when the component unmounts.
