|
| 1 | +# useIdle |
| 2 | + |
| 3 | +A hook to detect idle state of user. Idle state means user have not interacted with the page for a while. |
| 4 | + |
| 5 | +<pre>{`import { useIdle } from 'react-use-custom-hooks';`}</pre> |
| 6 | + |
| 7 | +### Usage example |
| 8 | + |
| 9 | +```typescript |
| 10 | +const idle = useIdle(5000); |
| 11 | +``` |
| 12 | + |
| 13 | +### Playground |
| 14 | + |
| 15 | +Pass the timeout value in milliseconds to `useIdle` hook as the first parameter. Default timeout is 2000ms. |
| 16 | + |
| 17 | +```jsx live |
| 18 | +function IdleExample(props) { |
| 19 | + const idle = useIdle(3000); |
| 20 | + |
| 21 | + return ( |
| 22 | + <> |
| 23 | + <p> |
| 24 | + User is <b>{idle ? 'idle' : 'active'}</b> |
| 25 | + </p> |
| 26 | + </> |
| 27 | + ); |
| 28 | +} |
| 29 | +``` |
| 30 | + |
| 31 | +#### Events |
| 32 | + |
| 33 | +By default this hook will listen to `keydown`, `mousemove`, `mousedown`, `touchmove`, `touchstart`, `click` and `scroll` events. You can pass `events` array in `options` parameter to listen to additional events. |
| 34 | + |
| 35 | +```jsx live |
| 36 | +function IdleExampleWithEvents(props) { |
| 37 | + const idle = useIdle(3000, { events: ['resize'] }); |
| 38 | + |
| 39 | + return ( |
| 40 | + <> |
| 41 | + <p> |
| 42 | + User is <b>{idle ? 'idle' : 'active'}</b> |
| 43 | + </p> |
| 44 | + </> |
| 45 | + ); |
| 46 | +} |
| 47 | +``` |
| 48 | + |
| 49 | +#### Listen only to specific events |
| 50 | + |
| 51 | +Pass `onlyPropEvents` value `true` in `options` object to listen only to events passed in `events` in options. |
| 52 | + |
| 53 | +```jsx live |
| 54 | +function IdleExampleWithEvents(props) { |
| 55 | + const idle = useIdle(3000, { events: ['click'], onlyPropEvents: true }); |
| 56 | + |
| 57 | + return ( |
| 58 | + <> |
| 59 | + <p> |
| 60 | + User not clicked for last 3 seconds - <b>{idle ? 'yes' : 'no'}</b> |
| 61 | + </p> |
| 62 | + </> |
| 63 | + ); |
| 64 | +} |
| 65 | +``` |
| 66 | + |
| 67 | +### API |
| 68 | + |
| 69 | +```typescript |
| 70 | +interface Options { |
| 71 | + events?: Array<string>; |
| 72 | + initialState?: boolean; |
| 73 | + onlyPropEvents?: boolean; |
| 74 | +} |
| 75 | + |
| 76 | +export function useIdle(timeout: number, options: Options): void; |
| 77 | +``` |
| 78 | + |
| 79 | +#### Options |
| 80 | + |
| 81 | +| Property | Description | Type | Default | |
| 82 | +| -------------- | --------------------------------------------------------------------------- | --------------- | ------- | |
| 83 | +| events | List of events to be listen to track idle status | `Array<string>` | `[]` | |
| 84 | +| initialState | Initial state of hook | `Boolean` | `true` | |
| 85 | +| onlyPropEvents | Pass `true` to listen only to the events passed in props for idle detection | `Boolean` | `false` | |
0 commit comments