Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Throttle component #16

Merged
merged 2 commits into from
Nov 18, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ yarn add react-recipes
| 🥑 [`useOnClickOutside`](#-useOnClickOutside) | - | (ref, callback) |
madrich27times marked this conversation as resolved.
Show resolved Hide resolved
| 🍿 [`usePrevious`](#-usePrevious) | previous | (value) |
| 🍣 [`useScript`](#-useScript) | [loaded, error] | (src) |
| 🍏 [`useThrottle`](#-useThrottle) | throttledValue | (value, ms: 250) |
| 🍷 [`useWhyDidYouUpdate`](#-useWhyDidYouUpdate) | - | (name, props) |
| 🥖 [`useWindowScroll`](#-useWindowScroll) | { x, y } | - |
| 🥮 [`useWindowSize`](#-useWindowSize) | { height, width } | (initialWidth, initialHeight) |
Expand Down Expand Up @@ -572,6 +573,35 @@ function App() {
```


### 🍏 `useThrottle`

Throttles a value

#### Arguments

- `value: Any`: The value to be throttled
- `ms: Number`: The time in milliseconds to throttle

#### Returns

- `throttledValue: Any`: The returned value after the throttling

```js
import { useThrottle } from "react-recipes";

const App = ({ value }) => {
const throttledValue = useThrottle(value, 250);

return (
<>
<div>Value: {value}</div>
<div>Throttled value: {throttledValue}</div>
</>
);
};
```


### 🍷 `useWhyDidYouUpdate`

Console logs the reason for why a component updated
Expand Down
71 changes: 71 additions & 0 deletions __tests__/useThrottle.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { renderHook } from '@testing-library/react-hooks';
import useThrottle from '../src/useThrottle';

describe('useThrottle', () => {
beforeAll(() => {
jest.useFakeTimers();
});

afterEach(() => {
jest.clearAllTimers();
});

// afterAll(() => {
madrich27times marked this conversation as resolved.
Show resolved Hide resolved
// jest.useRealTimers();
// });

it('should be defined', () => {
expect(useThrottle).toBeDefined();
});

it('should have a value to be returned', () => {
const { result } = renderHook(() => useThrottle(0, 100));
expect(result.current).toBe(0);
});

it('should has same value if time is advanced less than the given time', () => {
const { result, rerender } = renderHook(props => useThrottle(props, 100), { initialProps: 0 });
expect(result.current).toBe(0);
rerender(1);
jest.advanceTimersByTime(50);
expect(result.current).toBe(0);
});

it('should update the value after the given time when prop change', () => {
const hook = renderHook(props => useThrottle(props, 100), { initialProps: 0 });
expect(hook.result.current).toBe(0);
hook.rerender(1);
expect(hook.result.current).toBe(0);
hook.waitForNextUpdate().then(() => {
expect(hook.result.current).toBe(1);
});
jest.advanceTimersByTime(100);
});

it('should use the default ms value when missing', () => {
const hook = renderHook(props => useThrottle(props), { initialProps: 0 });
expect(hook.result.current).toBe(0);
hook.rerender(1);
hook.waitForNextUpdate().then(() => {
expect(hook.result.current).toBe(1);
});
jest.advanceTimersByTime(200);
});

it('should not update the value after the given time', () => {
const hook = renderHook(props => useThrottle(props, 100), { initialProps: 0 });
expect(hook.result.current).toBe(0);
jest.advanceTimersByTime(100);
expect(hook.result.current).toBe(0);
});

it('should cancel timeout on unmount', () => {
const hook = renderHook(props => useThrottle(props, 100), { initialProps: 0 });
expect(hook.result.current).toBe(0);
hook.rerender(1);
hook.unmount();
expect(jest.getTimerCount()).toBe(0);
jest.advanceTimersByTime(100);
expect(hook.result.current).toBe(0);
});
});
48 changes: 48 additions & 0 deletions src/useThrottle.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { useEffect, useRef, useState } from 'react';

const useThrottle = (value, ms = 200) => {
const [state, setState] = useState(value);
const timeout = useRef();
const nextValue = useRef(null);
const hasNextValue = useRef(0);

useEffect(() => {
if (!timeout.current) {
setState(value);
const timeoutCallback = () => {
if (hasNextValue.current) {
hasNextValue.current = false;
setState(nextValue.current);
timeout.current = setTimeout(timeoutCallback, ms);
} else {
timeout.current = undefined;
}
};
timeout.current = setTimeout(timeoutCallback, ms);
} else {
nextValue.current = value;
hasNextValue.current = true;
}
}, [value]);

// clear on unmount
useEffect(() => () => timeout.current && clearTimeout(timeout.current));

return state;
};

export default useThrottle;


// Usage

// const App = ({ value }) => {
// const throttledValue = useThrottle(value, 250);

// return (
// <>
// <div>Value: {value}</div>
// <div>Throttled value: {throttledValue}</div>
// </>
// );
// };