UNPKG

@ducor/hooks

Version:

A collection of useful React hooks for building modern web applications. Includes hooks for clipboard operations, window events, intervals, timeouts, and more.

38 lines (37 loc) 1.18 kB
import { useEffect, useRef, useState } from "react"; const DEFAULT_EVENTS = [ "keypress", "mousemove", "touchmove", "click", "scroll", ]; const DEFAULT_OPTIONS = { events: DEFAULT_EVENTS, initialState: true, }; /** * `useIdle` is a custom hook that detects whether the user has been idle for a certain amount of time in milliseconds. * */ const useIdle = (timeout = 3000, options) => { const { events, initialState } = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options); const [idle, setIdle] = useState(initialState); const timeoutId = useRef(null); useEffect(() => { const handleEvent = () => { setIdle(false); if (timeoutId.current) window.clearTimeout(timeoutId.current); timeoutId.current = window.setTimeout(() => { setIdle(true); }, timeout); }; events.forEach((event) => document.addEventListener(event, handleEvent)); return () => { events.forEach((event) => document.removeEventListener(event, handleEvent)); }; }, [events, timeout]); return idle; }; export default useIdle;