-
Notifications
You must be signed in to change notification settings - Fork 65
feat(core/hooks): add 'useThrottledCallback' hook #342
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
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
453ee87
feat(core/hooks): add 'useThrottledCallback' hook
sukvvon e6e4bc4
chore(changeset): add changeset for 'useThrottledCallback' hook
sukvvon 4a042c4
test(useThrottledCallback): add 'vi.useRealTimers' in 'afterEach'
sukvvon cec3206
refactor(useThrottledCallback): use named function in 'useEffect', re…
sukvvon File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| 'react-simplikit': patch | ||
| --- | ||
|
|
||
| feat(core/hooks): add 'useThrottledCallback' hook |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export { useThrottledCallback } from './useThrottledCallback.ts'; |
65 changes: 65 additions & 0 deletions
65
packages/core/src/hooks/useThrottledCallback/ko/useThrottledCallback.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| # useThrottledCallback | ||
|
|
||
| 제공된 콜백 함수의 스로틀링된 버전을 반환하는 React 훅이에요. 스로틀링된 콜백은 지정된 간격당 최대 한 번만 호출돼요. | ||
|
|
||
| ## Interface | ||
|
|
||
| ```ts | ||
| function useThrottledCallback<F extends (...args: any[]) => any>( | ||
| callback: F, | ||
| wait: number, | ||
| options?: { edges?: Array<'leading' | 'trailing'> } | ||
| ): F & { cancel: () => void }; | ||
| ``` | ||
|
|
||
| ### 파라미터 | ||
|
|
||
| <Interface | ||
| required | ||
| name="callback" | ||
| type="F" | ||
| description="스로틀링할 함수예요." | ||
| /> | ||
|
|
||
| <Interface | ||
| required | ||
| name="wait" | ||
| type="number" | ||
| description="호출을 스로틀링할 밀리초의 수예요." | ||
| /> | ||
|
|
||
| <Interface | ||
| name="options" | ||
| type="{ edges?: Array<'leading' | 'trailing'> }" | ||
| description="스로틀의 동작을 제어하기 위한 옵션이에요." | ||
| :nested="[ | ||
| { | ||
| name: 'options.edges', | ||
| type: 'Array<\'leading\' | \'trailing\'>', | ||
| required: false, | ||
| defaultValue: '[\'leading\', \'trailing\']', | ||
| description: | ||
| '함수가 시작점, 끝점 또는 둘 다에서 호출될지 여부를 지정하는 선택적 배열이에요. <br />: 초기값은 <code>[\'leading\', \'trailing\']</code>이에요.', | ||
| }, | ||
| ]" | ||
| /> | ||
|
|
||
| ### 반환 값 | ||
|
|
||
| <Interface | ||
| name="" | ||
| type="F & { cancel: () => void }" | ||
| description="보류 중인 호출을 취소하는 <code>cancel</code> 메서드가 있는 스로틀링된 함수가 반환돼요." | ||
| /> | ||
|
|
||
| ## 예시 | ||
|
|
||
| ```tsx | ||
| function SearchInput() { | ||
| const throttledSearch = useThrottledCallback((query: string) => { | ||
| console.log('검색어:', query); | ||
| }, 300); | ||
|
|
||
| return <input onChange={e => throttledSearch(e.target.value)} />; | ||
| } | ||
| ``` |
65 changes: 65 additions & 0 deletions
65
packages/core/src/hooks/useThrottledCallback/useThrottledCallback.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| # useThrottledCallback | ||
|
|
||
| `useThrottledCallback` is a React hook that returns a throttled version of the provided callback function. The throttled callback will only be invoked at most once per specified interval. | ||
|
|
||
| ## Interface | ||
|
|
||
| ```ts | ||
| function useThrottledCallback<F extends (...args: any[]) => any>( | ||
| callback: F, | ||
| wait: number, | ||
| options?: { edges?: Array<'leading' | 'trailing'> } | ||
| ): F & { cancel: () => void }; | ||
| ``` | ||
|
|
||
| ### Parameters | ||
|
|
||
| <Interface | ||
| required | ||
| name="callback" | ||
| type="F" | ||
| description="The function to throttle." | ||
| /> | ||
|
|
||
| <Interface | ||
| required | ||
| name="wait" | ||
| type="number" | ||
| description="The number of milliseconds to throttle invocations to." | ||
| /> | ||
|
|
||
| <Interface | ||
| name="options" | ||
| type="{ edges?: Array<'leading' | 'trailing'> }" | ||
| description="Options to control the behavior of the throttle." | ||
| :nested="[ | ||
| { | ||
| name: 'options.edges', | ||
| type: 'Array<\'leading\' | \'trailing\'>', | ||
| required: false, | ||
| defaultValue: '[\'leading\', \'trailing\']', | ||
| description: | ||
| 'An optional array specifying whether the function should be invoked on the leading edge, trailing edge, or both. <br />: The initial value is <code>[\'leading\', \'trailing\']</code>.', | ||
| }, | ||
| ]" | ||
| /> | ||
|
|
||
| ### Return Value | ||
|
|
||
| <Interface | ||
| name="" | ||
| type="F & { cancel: () => void }" | ||
| description="Returns the throttled function with a <code>cancel</code> method to cancel any pending invocation." | ||
| /> | ||
|
|
||
| ## Example | ||
|
|
||
| ```tsx | ||
| function SearchInput() { | ||
| const throttledSearch = useThrottledCallback((query: string) => { | ||
| console.log('Searching for:', query); | ||
| }, 300); | ||
|
|
||
| return <input onChange={e => throttledSearch(e.target.value)} />; | ||
| } | ||
| ``` |
114 changes: 114 additions & 0 deletions
114
packages/core/src/hooks/useThrottledCallback/useThrottledCallback.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; | ||
|
|
||
| import { renderHookSSR } from '../../_internal/test-utils/renderHookSSR.tsx'; | ||
|
|
||
| import { useThrottledCallback } from './useThrottledCallback.ts'; | ||
|
|
||
| describe('useThrottledCallback', () => { | ||
| beforeEach(() => { | ||
| vi.useFakeTimers(); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| vi.useRealTimers(); | ||
| }); | ||
|
|
||
| it('is safe on server side rendering', () => { | ||
| const onChange = vi.fn(); | ||
| renderHookSSR.serverOnly(() => useThrottledCallback({ onChange, timeThreshold: 100 })); | ||
|
|
||
| expect(onChange).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('should throttle the callback with the specified time threshold', () => { | ||
| const onChange = vi.fn(); | ||
| const { result } = renderHookSSR(() => useThrottledCallback({ onChange, timeThreshold: 100 })); | ||
|
|
||
| result.current(true); | ||
| expect(onChange).toBeCalledTimes(1); | ||
| expect(onChange).toBeCalledWith(true); | ||
|
|
||
| result.current(true); | ||
| vi.advanceTimersByTime(50); | ||
| expect(onChange).toBeCalledTimes(1); | ||
|
|
||
| vi.advanceTimersByTime(50); | ||
| expect(onChange).toBeCalledTimes(1); | ||
| }); | ||
|
|
||
| it('should call on leading edge by default', () => { | ||
| const onChange = vi.fn(); | ||
| const { result } = renderHookSSR(() => useThrottledCallback({ onChange, timeThreshold: 100 })); | ||
|
|
||
| result.current(true); | ||
| expect(onChange).toBeCalledTimes(1); | ||
| expect(onChange).toBeCalledWith(true); | ||
| }); | ||
|
|
||
| it('should handle trailing edge', () => { | ||
| const onChange = vi.fn(); | ||
| const { result } = renderHookSSR(() => useThrottledCallback({ onChange, timeThreshold: 100, edges: ['trailing'] })); | ||
|
|
||
| result.current(true); | ||
| expect(onChange).not.toBeCalled(); | ||
|
|
||
| vi.advanceTimersByTime(100); | ||
| expect(onChange).toBeCalledTimes(1); | ||
| expect(onChange).toBeCalledWith(true); | ||
| }); | ||
|
|
||
| it('should not trigger callback if value has not changed', () => { | ||
| const onChange = vi.fn(); | ||
| const { result } = renderHookSSR(() => useThrottledCallback({ onChange, timeThreshold: 100 })); | ||
|
|
||
| result.current(true); | ||
| vi.advanceTimersByTime(100); | ||
| expect(onChange).toBeCalledTimes(1); | ||
|
|
||
| result.current(true); | ||
| vi.advanceTimersByTime(100); | ||
| expect(onChange).toBeCalledTimes(1); | ||
| }); | ||
|
|
||
| it('should cleanup on unmount', async () => { | ||
| const onChange = vi.fn(); | ||
| const { result, unmount } = await renderHookSSR(() => | ||
| useThrottledCallback({ onChange, timeThreshold: 100, edges: ['trailing'] }) | ||
| ); | ||
|
|
||
| result.current(true); | ||
| unmount(); | ||
| vi.advanceTimersByTime(100); | ||
|
|
||
| expect(onChange).not.toBeCalled(); | ||
| }); | ||
|
|
||
| it('should handle leading and trailing edges together', () => { | ||
| const onChange = vi.fn(); | ||
| const { result } = renderHookSSR(() => | ||
| useThrottledCallback({ onChange, timeThreshold: 100, edges: ['leading', 'trailing'] }) | ||
| ); | ||
|
|
||
| result.current(true); | ||
| expect(onChange).toBeCalledTimes(1); | ||
| expect(onChange).toBeCalledWith(true); | ||
|
|
||
| vi.advanceTimersByTime(100); | ||
| expect(onChange).toBeCalledTimes(1); | ||
| }); | ||
|
|
||
| it('should handle value toggling', () => { | ||
| const onChange = vi.fn(); | ||
| const { result } = renderHookSSR(() => useThrottledCallback({ onChange, timeThreshold: 100 })); | ||
|
|
||
| result.current(true); | ||
| expect(onChange).toBeCalledTimes(1); | ||
| expect(onChange).toBeCalledWith(true); | ||
|
|
||
| vi.advanceTimersByTime(100); | ||
|
|
||
| result.current(false); | ||
| expect(onChange).toBeCalledTimes(2); | ||
| expect(onChange).toBeCalledWith(false); | ||
| }); | ||
| }); |
76 changes: 76 additions & 0 deletions
76
packages/core/src/hooks/useThrottledCallback/useThrottledCallback.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| import { useCallback, useEffect, useRef } from 'react'; | ||
|
|
||
| import { usePreservedCallback } from '../usePreservedCallback/index.ts'; | ||
| import { usePreservedReference } from '../usePreservedReference/index.ts'; | ||
| import { throttle } from '../useThrottle/throttle.ts'; | ||
|
|
||
| type ThrottleOptions = { | ||
| edges?: Array<'leading' | 'trailing'>; | ||
| }; | ||
|
|
||
| /** | ||
| * @description | ||
| * `useThrottledCallback` is a React hook that returns a throttled version of the provided callback function. | ||
| * The throttled callback will only be invoked at most once per specified interval. | ||
| * | ||
| * @param {Object} options - The options object. | ||
| * @param {Function} options.onChange - The callback function to throttle. | ||
| * @param {number} options.timeThreshold - The number of milliseconds to throttle invocations to. | ||
| * @param {Array<'leading' | 'trailing'>} [options.edges=['leading', 'trailing']] - An optional array specifying whether the function should be invoked on the leading edge, trailing edge, or both. | ||
| * | ||
| * @returns {Function} A throttled function that limits invoking the callback. | ||
| * | ||
| * @example | ||
| * function ScrollTracker() { | ||
| * const throttledScroll = useThrottledCallback({ | ||
| * onChange: (scrollY: number) => console.log(scrollY), | ||
| * timeThreshold: 200, | ||
| * }); | ||
| * return <div onScroll={(e) => throttledScroll(e.currentTarget.scrollTop)} />; | ||
| * } | ||
| */ | ||
| export function useThrottledCallback({ | ||
| onChange, | ||
| timeThreshold, | ||
| edges = ['leading', 'trailing'], | ||
| }: ThrottleOptions & { | ||
| onChange: (newValue: boolean) => void; | ||
| timeThreshold: number; | ||
| }) { | ||
| const handleChange = usePreservedCallback(onChange); | ||
| const ref = useRef({ value: false, clearPreviousThrottle: () => {} }); | ||
|
|
||
| useEffect(function cleanupThrottleOnUnmount() { | ||
| const current = ref.current; | ||
| return () => { | ||
| current.clearPreviousThrottle(); | ||
| }; | ||
| }, []); | ||
|
|
||
| const preservedEdges = usePreservedReference(edges); | ||
|
|
||
| return useCallback( | ||
| (nextValue: boolean) => { | ||
| if (nextValue === ref.current.value) { | ||
| return; | ||
| } | ||
|
|
||
| const throttled = throttle( | ||
| () => { | ||
| handleChange(nextValue); | ||
|
|
||
| ref.current.value = nextValue; | ||
| }, | ||
| timeThreshold, | ||
| { edges: preservedEdges } | ||
| ); | ||
|
|
||
| ref.current.clearPreviousThrottle(); | ||
|
|
||
| throttled(); | ||
|
|
||
| ref.current.clearPreviousThrottle = throttled.cancel; | ||
| }, | ||
| [handleChange, timeThreshold, preservedEdges] | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Note:
onChangeis currently boolean-only, matching useDebouncedCallback's current API. PR #267 extends useDebouncedCallback to generic<T>— after that merges, a follow-up to make useThrottledCallback generic as well would be welcome.