Skip to content

Commit

Permalink
feat: add useThrottle hook
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich authored Mar 26, 2019
2 parents 9312202 + c9d7b52 commit 756bc99
Show file tree
Hide file tree
Showing 7 changed files with 127 additions and 2 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,13 @@
- [**Side-effects**](./docs/Side-effects.md)
- [`useAsync`](./docs/useAsync.md) — resolves an `async` function.
- [`useAsyncRetry`](./docs/useAsyncRetry.md) — `useAsync` with `retry()` method.
- [`useDebounce`](./docs/useDebounce.md) — debounces a function. [![][img-demo]](https://streamich.github.io/react-use/?path=/story/side-effects-usedebounce--demo)
- [`useFavicon`](./docs/useFavicon.md) — sets favicon of the page.
- [`useLocalStorage`](./docs/useLocalStorage.md) — manages a value in `localStorage`.
- [`useLockBodyScroll`](./docs/useLockBodyScroll.md) — lock scrolling of the body element.
- [`useSessionStorage`](./docs/useSessionStorage.md) — manages a value in `sessionStorage`.
- [`useThrottle`](./docs/useThrottle.md) — throttles a function. [![][img-demo]](https://streamich.github.io/react-use/?path=/story/side-effects-usethrottle--demo)
- [`useTitle`](./docs/useTitle.md) — sets title of the page.
- [`useDebounce`](./docs/useDebounce.md) — debounces a function.
<br/>
<br/>
- [**Lifecycles**](./docs/Lifecycles.md)
Expand Down
5 changes: 4 additions & 1 deletion docs/useDebounce.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@ import { useDebounce } from 'react-use';
const Demo = () => {
const [state, setState] = React.useState('Typing stopped');
const [val, setVal] = React.useState('');
const [debouncedValue, setDebouncedValue] = React.useState('');

useDebounce(
() => {
setState('Typing stopped');
setDebouncedValue(val);
},
2000,
[val]
Expand All @@ -34,6 +36,7 @@ const Demo = () => {
}}
/>
<div>{state}</div>
<div>Debounced value: {debouncedValue}</div>
</div>
);
};
Expand All @@ -42,5 +45,5 @@ const Demo = () => {
## Reference

```ts
useDebouce(fn, ms: number, args: any[]);
useDebounce(fn, ms: number, args: any[]);
```
49 changes: 49 additions & 0 deletions docs/useThrottle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# `useThrottle`

React hook that invokes a function and then delays subsequent function calls until after wait milliseconds have elapsed since the last time the throttled function was invoked.

The third argument is the array of values that the throttle depends on, in the same manner as useEffect. The throttle timeout will start when one of the values changes.

## Usage

```jsx
import React, { useState } from 'react';
import { useThrottle } from 'react-use';

const Demo = () => {
const [status, setStatus] = React.useState('Updating stopped');
const [value, setValue] = React.useState('');
const [throttledValue, setThrottledValue] = React.useState('');

useThrottle(
() => {
setStatus('Waiting for input...');
setThrottledValue(value);
},
2000,
[value]
);

return (
<div>
<input
type="text"
value={value}
placeholder="Throttled input"
onChange={({ currentTarget }) => {
setStatus('Updating stopped');
setValue(currentTarget.value);
}}
/>
<div>{status}</div>
<div>Throttled value: {throttledValue}</div>
</div>
);
};
```

## Reference

```ts
useThrottle(fn, ms: number, args: any[]);
```
3 changes: 3 additions & 0 deletions src/__stories__/useDebounce.story.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ import ShowDocs from '../util/ShowDocs';
const Demo = () => {
const [state, setState] = React.useState('Typing stopped');
const [val, setVal] = React.useState('');
const [debouncedValue, setDebouncedValue] = React.useState('');

useDebounce(
() => {
setState('Typing stopped');
setDebouncedValue(val);
},
2000,
[val]
Expand All @@ -27,6 +29,7 @@ const Demo = () => {
}}
/>
<div>{state}</div>
<div>Debounced value: {debouncedValue}</div>
</div>
);
};
Expand Down
39 changes: 39 additions & 0 deletions src/__stories__/useThrottle.story.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import * as React from 'react';
import { storiesOf } from '@storybook/react';
import { useThrottle } from '..';
import ShowDocs from '../util/ShowDocs';

const Demo = () => {
const [status, setStatus] = React.useState('Updating stopped');
const [value, setValue] = React.useState('');
const [throttledValue, setThrottledValue] = React.useState('');

useThrottle(
() => {
setStatus('Waiting for input...');
setThrottledValue(value);
},
2000,
[value]
);

return (
<div>
<input
type="text"
value={value}
placeholder="Throttled input"
onChange={({ currentTarget }) => {
setStatus('Updating stopped');
setValue(currentTarget.value);
}}
/>
<div>{status}</div>
<div>Throttled value: {throttledValue}</div>
</div>
);
};

storiesOf('Side effects|useThrottle', module)
.add('Docs', () => <ShowDocs md={require('../../docs/useThrottle.md')} />)
.add('Demo', () => <Demo />);
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import useSetState from './useSetState';
import useSize from './useSize';
import useSpeech from './useSpeech';
import useSpring from './useSpring';
import useThrottle from './useThrottle';
import useTimeout from './useTimeout';
import useTitle from './useTitle';
import useToggle from './useToggle';
Expand Down Expand Up @@ -101,6 +102,7 @@ export {
useSize,
useSpeech,
useSpring,
useThrottle,
useTimeout,
useTitle,
useToggle,
Expand Down
28 changes: 28 additions & 0 deletions src/useThrottle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { useRef, useEffect } from 'react';

const useThrottle = (fn: () => any, ms: number = 0, args?) => {
const lastRan = useRef(0);

useEffect(() => {
let timeout
const diff = Date.now() - lastRan.current

if (diff >= ms) {
fn.apply(null, args);
lastRan.current = Date.now();
} else {
timeout = setTimeout(() => {
fn.apply(null, args);
lastRan.current = Date.now();
}, ms - diff)
}

return () => {
if (timeout) {
clearTimeout(timeout);
}
}
}, args);
};

export default useThrottle;

0 comments on commit 756bc99

Please sign in to comment.