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

Feature: add useThrottle hook #629

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ function Component() {
- [`useSessionStorage`](https://usehooks-ts.com/react-hook/use-session-storage) — uses the [sessionStorage API](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) to persist state across page reloads.
- [`useStep`](https://usehooks-ts.com/react-hook/use-step) — manages and navigates between steps in a multi-step process.
- [`useTernaryDarkMode`](https://usehooks-ts.com/react-hook/use-ternary-dark-mode) — manages ternary (system, dark, light) dark mode with local storage support.
- [`useThrottle`](https://usehooks-ts.com/react-hook/use-throttle) — A custom hooks that support throttle.
- [`useTimeout`](https://usehooks-ts.com/react-hook/use-timeout) — handles timeouts in React components using the [setTimeout API](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout).
- [`useToggle`](https://usehooks-ts.com/react-hook/use-toggle) — manages a boolean toggle state in React components.
- [`useUnmount`](https://usehooks-ts.com/react-hook/use-unmount) — runs a cleanup function when the component is unmounted.
Expand Down
1 change: 1 addition & 0 deletions packages/usehooks-ts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ function Component() {
- [`useSessionStorage`](https://usehooks-ts.com/react-hook/use-session-storage) — uses the [sessionStorage API](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) to persist state across page reloads.
- [`useStep`](https://usehooks-ts.com/react-hook/use-step) — manages and navigates between steps in a multi-step process.
- [`useTernaryDarkMode`](https://usehooks-ts.com/react-hook/use-ternary-dark-mode) — manages ternary (system, dark, light) dark mode with local storage support.
- [`useThrottle`](https://usehooks-ts.com/react-hook/use-throttle) — A custom hook that support throttle.
- [`useTimeout`](https://usehooks-ts.com/react-hook/use-timeout) — handles timeouts in React components using the [setTimeout API](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout).
- [`useToggle`](https://usehooks-ts.com/react-hook/use-toggle) — manages a boolean toggle state in React components.
- [`useUnmount`](https://usehooks-ts.com/react-hook/use-unmount) — runs a cleanup function when the component is unmounted.
Expand Down
1 change: 1 addition & 0 deletions packages/usehooks-ts/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export * from './useScrollLock'
export * from './useSessionStorage'
export * from './useStep'
export * from './useTernaryDarkMode'
export * from './useThrottle'
export * from './useTimeout'
export * from './useToggle'
export * from './useUnmount'
Expand Down
1 change: 1 addition & 0 deletions packages/usehooks-ts/src/useThrottle/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './useThrottle'
24 changes: 24 additions & 0 deletions packages/usehooks-ts/src/useThrottle/useThrottle.demo.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { useState } from 'react'

import { useEventListener } from 'src/useEventListener'

import { useThrottle } from './useThrottle'

export default function Component() {
const [state, setState] = useState<number>(0)
const throttle = useThrottle()

const onScroll = () => {
throttle(() => {
setState(state => state + 1)
}, 1000)
}

useEventListener('scroll', onScroll)

return (
<div>
<span>{state}</span>
</div>
)
}
5 changes: 5 additions & 0 deletions packages/usehooks-ts/src/useThrottle/useThrottle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Use the throttle function with one simple function

Related hooks:

- [`useThrottle()`](/react-hook/use-throttle)
62 changes: 62 additions & 0 deletions packages/usehooks-ts/src/useThrottle/useThrottle.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { useState } from 'react'

import { act, renderHook } from '@testing-library/react'

import { useThrottle } from './useThrottle'

describe('use throttle()', () => {
it('shoud use thorttle be ok', () => {
const { result } = renderHook(() => useThrottle())
const throttle = result.current

expect(typeof throttle).toBe('function')
})

it('shoud default value works', () => {
const countRender = renderHook(() => useState(0))
const [count, setCount] = countRender.result.current

const throttleRender = renderHook(() => useThrottle())
const throttle = throttleRender.result.current

act(() => {
throttle(() => {
setCount(state => state + 1)
})

throttle(() => {
setCount(state => state + 1)
})

setTimeout(() => {
expect(count).toBe(1)
}, 1000)
})
})

it('shoud interval param works', () => {
const countRender = renderHook(() => useState(0))
const [count, setCount] = countRender.result.current

const throttleRender = renderHook(() => useThrottle())
const throttle = throttleRender.result.current

act(() => {
throttle(() => {
setCount(state => state + 1)
}, 1)

throttle(() => {
setCount(state => state + 1)
}, 1)

throttle(() => {
setCount(state => state + 1)
}, 2)

setTimeout(() => {
expect(count).toBe(2)
}, 1000)
})
})
})
33 changes: 33 additions & 0 deletions packages/usehooks-ts/src/useThrottle/useThrottle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { useRef } from 'react'

/**
* Custom hook that provides a stottle function.
* @param {number} [defaultInterval] - The initial value for the throttle interval.
* @returns {(callback: () => void, interval?: number) => void} An executable throttle function
* a function to executed after a certain period of time based on the last function among the functions that are executed quickly.
* @public
* @see [Documentation](https://usehooks-ts.com/react-hook/use-throttle)
* @example
* ```tsx
* const throttle = useThrottle(2000); // Initial value is 2s
* // OR
* const throttle = useThrottle(); // Initial value is default value (1s)
* // Use throttle function in your component, Only one of the events that are processed redundantly can be processed.
* ```
*/

export function useThrottle(
defaultInterval = 1000,
): (callback: () => void, interval?: number) => void {
const ref = useRef<ReturnType<typeof setTimeout>>()

const throttle = (callback: () => void, interval?: number) => {
if (ref.current !== undefined) {
clearTimeout(ref.current)
}

ref.current = setTimeout(callback, interval ?? defaultInterval)
}

return throttle
}