From 4a5333b6f90bd62931fc6ad486ea17be9d772bbe Mon Sep 17 00:00:00 2001 From: Antoliny0919 Date: Thu, 19 Nov 2026 10:17:05 +0900 Subject: [PATCH 1/2] refactor(useDebounce, useThrottle): reuse internal implementations for deprecated hooks - These hooks are deprecated but are still used internally --- .../_internal/useDebounce/useDebounce.ts | 4 +- .../_internal/useThrottle/useThrottle.ts | 5 +- .../src/hooks/useDebounce/debounce.ts | 93 ------- .../src/hooks/useDebounce/useDebounce.spec.ts | 3 +- .../src/hooks/useDebounce/useDebounce.ts | 52 +--- .../src/hooks/useThrottle/throttle.spec.ts | 248 ------------------ .../src/hooks/useThrottle/throttle.ts | 80 ------ .../src/hooks/useThrottle/useThrottle.ts | 47 +--- 8 files changed, 11 insertions(+), 521 deletions(-) delete mode 100644 packages/react-simplikit/src/hooks/useDebounce/debounce.ts delete mode 100644 packages/react-simplikit/src/hooks/useThrottle/throttle.spec.ts delete mode 100644 packages/react-simplikit/src/hooks/useThrottle/throttle.ts diff --git a/packages/react-simplikit/src/hooks/_internal/useDebounce/useDebounce.ts b/packages/react-simplikit/src/hooks/_internal/useDebounce/useDebounce.ts index fc41b1e9..1d40cf53 100644 --- a/packages/react-simplikit/src/hooks/_internal/useDebounce/useDebounce.ts +++ b/packages/react-simplikit/src/hooks/_internal/useDebounce/useDebounce.ts @@ -4,7 +4,7 @@ import { useMemo } from 'react'; import type { CallerTypedArgs } from '../../../_internal/types.ts'; import { usePreservedCallback } from '../../usePreservedCallback/usePreservedCallback.ts'; -import { debounce, DebouncedFunction } from './debounce.ts'; +import { debounce } from './debounce.ts'; type DebounceOptions = { leading?: boolean; @@ -25,7 +25,7 @@ export function useDebounce unknown>( callback: F, debounceMs: number, options: DebounceOptions = {} -): DebouncedFunction { +): { (...args: Parameters): void; cancel: () => void } { const preservedCallback = usePreservedCallback(callback) as F; const { leading = false, trailing = true } = options; diff --git a/packages/react-simplikit/src/hooks/_internal/useThrottle/useThrottle.ts b/packages/react-simplikit/src/hooks/_internal/useThrottle/useThrottle.ts index b50f2650..7966b211 100644 --- a/packages/react-simplikit/src/hooks/_internal/useThrottle/useThrottle.ts +++ b/packages/react-simplikit/src/hooks/_internal/useThrottle/useThrottle.ts @@ -24,7 +24,10 @@ export function useThrottle unknown>( callback: F, throttleMs: number, { leading = true, trailing = true }: ThrottleOptions = {} -) { +): { + (...args: Parameters): void; + cancel: () => void; +} { const preservedCallback = usePreservedCallback(callback); const edges = useMemo(() => { diff --git a/packages/react-simplikit/src/hooks/useDebounce/debounce.ts b/packages/react-simplikit/src/hooks/useDebounce/debounce.ts deleted file mode 100644 index f332eb29..00000000 --- a/packages/react-simplikit/src/hooks/useDebounce/debounce.ts +++ /dev/null @@ -1,93 +0,0 @@ -// Simplified version of https://github.com/toss/es-toolkit/blob/main/src/function/debounce.ts - -import type { CallerTypedArgs } from '../../_internal/types.ts'; - -export type DebouncedFunction void> = { - (...args: Parameters): void; - cancel: () => void; -}; - -type DebounceOptions = { - /** - * An optional array specifying whether the function should be invoked on the leading edge, trailing edge, or both. - * If `edges` includes "leading", the function will be invoked at the start of the delay period. - * If `edges` includes "trailing", the function will be invoked at the end of the delay period. - * If both "leading" and "trailing" are included, the function will be invoked at both the start and end of the delay period. - * @default ["leading", "trailing"] - */ - edges?: Array<'leading' | 'trailing'>; -}; - -export function debounce void>( - func: F, - debounceMs: number, - { edges = ['leading', 'trailing'] }: DebounceOptions = {} -): DebouncedFunction & { schedule: () => void } { - let pendingThis: ThisParameterType | undefined = undefined; - let pendingArgs: Parameters | null = null; - - const leading = edges != null && edges.includes('leading'); - const trailing = edges == null || edges.includes('trailing'); - - const invoke = () => { - if (pendingArgs !== null) { - func.apply(pendingThis, pendingArgs); - pendingThis = undefined; - pendingArgs = null; - } - }; - - const onTimerEnd = () => { - if (trailing) { - invoke(); - } - - cancel(); - }; - - let timeoutId: ReturnType | null = null; - - const schedule = () => { - if (timeoutId != null) { - clearTimeout(timeoutId); - } - - timeoutId = setTimeout(() => { - timeoutId = null; - - onTimerEnd(); - }, debounceMs); - }; - - const cancelTimer = () => { - if (timeoutId !== null) { - clearTimeout(timeoutId); - timeoutId = null; - } - }; - - const cancel = () => { - cancelTimer(); - pendingThis = undefined; - pendingArgs = null; - }; - - const debounced = function (this: ThisParameterType, ...args: Parameters) { - // eslint-disable-next-line @typescript-eslint/no-this-alias - pendingThis = this; - pendingArgs = args; - - const isFirstCall = timeoutId == null; - - schedule(); - - if (leading && isFirstCall) { - invoke(); - } - }; - - debounced.schedule = schedule; - debounced.cancel = cancel; - - return debounced; -} diff --git a/packages/react-simplikit/src/hooks/useDebounce/useDebounce.spec.ts b/packages/react-simplikit/src/hooks/useDebounce/useDebounce.spec.ts index 940cade0..494fcb45 100644 --- a/packages/react-simplikit/src/hooks/useDebounce/useDebounce.spec.ts +++ b/packages/react-simplikit/src/hooks/useDebounce/useDebounce.spec.ts @@ -2,7 +2,6 @@ import { beforeEach, describe, expect, expectTypeOf, it, vi } from 'vitest'; import { renderHookSSR } from '../../_internal/test-utils/renderHookSSR.tsx'; -import { DebouncedFunction } from './debounce.ts'; import { useDebounce } from './useDebounce.ts'; describe('useDebounce', () => { @@ -83,7 +82,7 @@ describe('useDebounce', () => { const { result } = renderHookSSR(() => useDebounce(callback, 100)); - expectTypeOf(result.current).toEqualTypeOf>(); + expectTypeOf(result.current).toEqualTypeOf<{ (value: string): void; cancel: () => void }>(); }); it('should cleanup on unmount', async () => { diff --git a/packages/react-simplikit/src/hooks/useDebounce/useDebounce.ts b/packages/react-simplikit/src/hooks/useDebounce/useDebounce.ts index 288bfb3f..85ca2e6d 100644 --- a/packages/react-simplikit/src/hooks/useDebounce/useDebounce.ts +++ b/packages/react-simplikit/src/hooks/useDebounce/useDebounce.ts @@ -1,15 +1,4 @@ -import { useEffect } from 'react'; -import { useMemo } from 'react'; - -import type { CallerTypedArgs } from '../../_internal/types.ts'; -import { usePreservedCallback } from '../usePreservedCallback/index.ts'; - -import { debounce } from './debounce.ts'; - -type DebounceOptions = { - leading?: boolean; - trailing?: boolean; -}; +import { useDebounce as internalUseDebounce } from '../_internal/useDebounce/useDebounce.ts'; /** * @description @@ -66,41 +55,4 @@ type DebounceOptions = { * [`useDebouncedState`](/hooks/useDebouncedState) to debounce a state update, * or [`useDebouncedValue`](/hooks/useDebouncedValue) to get a debounced value. */ -export function useDebounce unknown>( - callback: F, - debounceMs: number, - options: DebounceOptions = {} - // Written out because `DebouncedFunction` is not exported from the package entry, so consumers emitting declarations cannot name it (TS2742) -): { (...args: Parameters): void; cancel: () => void } { - const preservedCallback = usePreservedCallback(callback) as F; - - const { leading = false, trailing = true } = options; - - const edges = useMemo(() => { - const _edges: Array<'leading' | 'trailing'> = []; - if (leading) { - _edges.push('leading'); - } - - if (trailing) { - _edges.push('trailing'); - } - - return _edges; - }, [leading, trailing]); - - const debounced = useMemo(() => { - return debounce(preservedCallback, debounceMs, { edges }); - }, [preservedCallback, debounceMs, edges]); - - useEffect( - function cancelDebouncedOnUnmount() { - return () => { - debounced.cancel(); - }; - }, - [debounced] - ); - - return debounced; -} +export const useDebounce = internalUseDebounce; diff --git a/packages/react-simplikit/src/hooks/useThrottle/throttle.spec.ts b/packages/react-simplikit/src/hooks/useThrottle/throttle.spec.ts deleted file mode 100644 index d844d563..00000000 --- a/packages/react-simplikit/src/hooks/useThrottle/throttle.spec.ts +++ /dev/null @@ -1,248 +0,0 @@ -import { describe, expect, it, vi } from 'vitest'; - -import { throttle } from './throttle.ts'; - -describe('throttle', () => { - it('should throttle function calls', async () => { - const func = vi.fn(); - const throttledFunc = throttle(func, 100); - - throttledFunc(); - throttledFunc(); - throttledFunc(); - - expect(func).toHaveBeenCalledTimes(1); - }); - - it('should trigger a trailing call as soon as possible', async () => { - vi.useFakeTimers(); - - const func = vi.fn(); - const throttleMs = 50; - - const throttled = throttle(func, throttleMs); - - throttled(); - throttled(); - expect(func).toBeCalledTimes(1); - - await vi.advanceTimersByTimeAsync(throttleMs + 1); - expect(func).toBeCalledTimes(2); - }); - - it('should execute the function immediately if not called within the wait time', async () => { - vi.useFakeTimers(); - - const func = vi.fn(); - const throttleMs = 500; - const throttledFunc = throttle(func, throttleMs); - - throttledFunc(); // should be executed - expect(func).toHaveBeenCalledTimes(1); - - await vi.advanceTimersByTimeAsync(throttleMs / 2); - expect(func).toHaveBeenCalledTimes(1); - - throttledFunc(); // should be ignored - expect(func).toHaveBeenCalledTimes(1); - - await vi.advanceTimersByTimeAsync(throttleMs / 2 + 1); - expect(func).toHaveBeenCalledTimes(1); - - throttledFunc(); // should be executed - expect(func).toHaveBeenCalledTimes(2); - - await vi.advanceTimersByTimeAsync(throttleMs / 2 - 1); - expect(func).toHaveBeenCalledTimes(2); - - throttledFunc(); // should be ignored - expect(func).toHaveBeenCalledTimes(2); - - await vi.advanceTimersByTimeAsync(throttleMs / 2 + 1); - expect(func).toHaveBeenCalledTimes(2); - - throttledFunc(); // should be executed - expect(func).toHaveBeenCalledTimes(3); - }); - - it('should call the function with correct arguments', async () => { - const func = vi.fn(); - const throttleMs = 50; - const throttledFunc = throttle(func, throttleMs); - - throttledFunc('test', 123); - - expect(func).toHaveBeenCalledTimes(1); - expect(func).toHaveBeenCalledWith('test', 123); - }); - - it('should not trigger a trailing call when invoked once', async () => { - const func = vi.fn(); - const throttleMs = 50; - - const throttled = throttle(func, throttleMs); - - throttled(); - expect(func).toBeCalledTimes(1); - - await vi.advanceTimersByTimeAsync(throttleMs + 1); - expect(func).toBeCalledTimes(1); - }); - - it('should invoke once per window while calls keep coming with trailing edge only', () => { - vi.useFakeTimers(); - - const func = vi.fn(); - const throttled = throttle(func, 100, { edges: ['trailing'] }); - - for (let i = 1; i <= 10; i++) { - throttled(i); - vi.advanceTimersByTime(30); - } - expect(func.mock.calls.map(call => call[0])).toEqual([5, 9]); - - vi.advanceTimersByTime(100); - expect(func.mock.calls.map(call => call[0])).toEqual([5, 9, 10]); - - vi.useRealTimers(); - }); - - it('should defer a call after an idle period with trailing edge only', () => { - vi.useFakeTimers(); - - const func = vi.fn(); - const throttled = throttle(func, 100, { edges: ['trailing'] }); - - throttled('a'); - expect(func).toHaveBeenCalledTimes(0); - - vi.advanceTimersByTime(100); - expect(func).toHaveBeenCalledTimes(1); - - vi.advanceTimersByTime(400); - throttled('b'); - expect(func).toHaveBeenCalledTimes(1); - - vi.advanceTimersByTime(100); - expect(func).toHaveBeenCalledTimes(2); - expect(func).toHaveBeenLastCalledWith('b'); - - vi.useRealTimers(); - }); - - it('should invoke once per window while calls keep coming with leading edge only', () => { - vi.useFakeTimers(); - - const func = vi.fn(); - const throttled = throttle(func, 100, { edges: ['leading'] }); - - for (let i = 1; i <= 10; i++) { - throttled(i); - vi.advanceTimersByTime(30); - } - vi.advanceTimersByTime(200); - - expect(func.mock.calls.map(call => call[0])).toEqual([1, 5, 9]); - - vi.useRealTimers(); - }); - - it('should forget the pending call on cancel', () => { - vi.useFakeTimers(); - - const func = vi.fn(); - const throttled = throttle(func, 100, { edges: ['trailing'] }); - - throttled('a'); - throttled.cancel(); - vi.advanceTimersByTime(500); - - throttled('b'); - expect(func).toHaveBeenCalledTimes(0); - - vi.advanceTimersByTime(100); - expect(func).toHaveBeenCalledTimes(1); - expect(func).toHaveBeenLastCalledWith('b'); - - vi.useRealTimers(); - }); - - it('should never invoke when edges is empty', () => { - vi.useFakeTimers(); - - const func = vi.fn(); - const throttled = throttle(func, 100, { edges: [] }); - - throttled('a'); - vi.advanceTimersByTime(100); - throttled('b'); - vi.advanceTimersByTime(300); - - expect(func).not.toHaveBeenCalled(); - - vi.useRealTimers(); - }); - - it('should keep deferring calls after an idle period until the reopened window elapses', () => { - vi.useFakeTimers(); - - const func = vi.fn(); - const throttled = throttle(func, 100, { edges: ['trailing'] }); - - throttled('a'); - vi.advanceTimersByTime(100); - expect(func).toHaveBeenCalledTimes(1); - expect(func).toHaveBeenLastCalledWith('a'); - - vi.advanceTimersByTime(200); - throttled('b'); - vi.advanceTimersByTime(10); - throttled('c'); - expect(func).toHaveBeenCalledTimes(1); - - vi.advanceTimersByTime(100); - expect(func).toHaveBeenCalledTimes(2); - expect(func).toHaveBeenLastCalledWith('c'); - - vi.useRealTimers(); - }); - - it('should use the actual invocation time, not the call time, as the start of the next window', () => { - vi.useFakeTimers(); - - const func = vi.fn(); - const throttled = throttle(func, 100, { edges: ['trailing'] }); - - throttled('a'); - vi.advanceTimersByTime(100); // the debounce timer fires here, invoking with 'a' - expect(func).toHaveBeenCalledTimes(1); - - vi.advanceTimersByTime(50); // 50ms after the invocation above - throttled('b'); - - vi.advanceTimersByTime(60); // 110ms after the invocation, so the window has elapsed - throttled('c'); - expect(func).toHaveBeenCalledTimes(2); - expect(func).toHaveBeenLastCalledWith('c'); - - vi.useRealTimers(); - }); - - it('should treat a call exactly throttleMs after the window start as elapsed', () => { - vi.useFakeTimers(); - - const func = vi.fn(); - const throttled = throttle(func, 100, { edges: ['trailing'] }); - - throttled('a'); - vi.advanceTimersByTime(50); - throttled('b'); - vi.advanceTimersByTime(50); - throttled('c'); - - expect(func).toHaveBeenCalledTimes(1); - expect(func).toHaveBeenLastCalledWith('c'); - - vi.useRealTimers(); - }); -}); diff --git a/packages/react-simplikit/src/hooks/useThrottle/throttle.ts b/packages/react-simplikit/src/hooks/useThrottle/throttle.ts deleted file mode 100644 index bdceb302..00000000 --- a/packages/react-simplikit/src/hooks/useThrottle/throttle.ts +++ /dev/null @@ -1,80 +0,0 @@ -// Simplified version of https://github.com/toss/es-toolkit/blob/main/src/function/throttle.ts - -import type { CallerTypedArgs } from '../../_internal/types.ts'; -import { debounce } from '../useDebounce/debounce.ts'; - -type ThrottleOptions = { - /** - * An optional array specifying whether the function should be invoked on the leading edge, trailing edge, or both. - * If `edges` includes "leading", the function will be invoked at the start of the delay period. - * If `edges` includes "trailing", the function will be invoked at the end of the delay period. - * If both "leading" and "trailing" are included, the function will be invoked at both the start and end of the delay period. - * @default ["leading", "trailing"] - */ - edges?: Array<'leading' | 'trailing'>; -}; - -type ThrottledFunction void> = { - (...args: Parameters): void; - cancel: () => void; -}; - -export function throttle void>( - func: F, - throttleMs: number, - { edges = ['leading', 'trailing'] }: ThrottleOptions = {} -): ThrottledFunction { - const leading = edges.includes('leading'); - const trailing = edges.includes('trailing'); - - let pendingAt: number | null = null; - // `true` while a call is waiting on the debounce timer. A trailing-only throttle uses it to tell a - // continuous stream of calls (invoke at the window boundary) from a call after an idle period - // (open a fresh window and invoke at its end). es-toolkit invokes at the boundary in both cases, - // which makes a trailing-only throttle fire on the leading edge after it has been idle. - let isPending = false; - - const debounced = debounce( - function (this: ThisParameterType, ...args: Parameters) { - pendingAt = Date.now(); - isPending = false; - func.apply(this, args); - }, - throttleMs, - { edges } - ); - - const throttled = function (this: ThisParameterType, ...args: Parameters) { - if (pendingAt === null) { - pendingAt = Date.now(); - } - - const windowElapsed = Date.now() - pendingAt >= throttleMs; - - if (windowElapsed && (leading || (trailing && isPending))) { - pendingAt = Date.now(); - isPending = false; - func.apply(this, args); - - // Re-arm the timer without arguments so the next call in this window does not count as a - // leading call for the debounce. - debounced.cancel(); - debounced.schedule(); - return; - } - - if (windowElapsed) { - pendingAt = Date.now(); - } - - isPending = true; - debounced.apply(this, args); - }; - - throttled.cancel = () => { - isPending = false; - debounced.cancel(); - }; - - return throttled; -} diff --git a/packages/react-simplikit/src/hooks/useThrottle/useThrottle.ts b/packages/react-simplikit/src/hooks/useThrottle/useThrottle.ts index dd53cc70..d21d2a74 100644 --- a/packages/react-simplikit/src/hooks/useThrottle/useThrottle.ts +++ b/packages/react-simplikit/src/hooks/useThrottle/useThrottle.ts @@ -1,14 +1,4 @@ -import { useEffect, useMemo } from 'react'; - -import type { CallerTypedArgs } from '../../_internal/types.ts'; -import { usePreservedCallback } from '../usePreservedCallback/index.ts'; - -import { throttle } from './throttle.ts'; - -type ThrottleOptions = { - leading?: boolean; - trailing?: boolean; -}; +import { useThrottle as internalUseThrottle } from '../_internal/useThrottle/useThrottle.ts'; /** * @description @@ -42,37 +32,4 @@ type ThrottleOptions = { * [`useThrottledState`](/hooks/useThrottledState) to throttle a state update, * or [`useThrottledValue`](/hooks/useThrottledValue) to get a throttled value. */ -export function useThrottle unknown>( - callback: F, - throttleMs: number, - { leading = true, trailing = true }: ThrottleOptions = {} - // Written out because the inferred type names `CallerTypedArgs`, which consumers emitting declarations cannot import (TS2742) -): { (...args: Parameters): void; cancel: () => void } { - const preservedCallback = usePreservedCallback(callback); - - const edges = useMemo(() => { - const _edges: Array<'leading' | 'trailing'> = []; - if (leading) { - _edges.push('leading'); - } - - if (trailing) { - _edges.push('trailing'); - } - - return _edges; - }, [leading, trailing]); - - const throttledCallback = useMemo( - () => throttle(preservedCallback, throttleMs, { edges }), - [preservedCallback, throttleMs, edges] - ); - - useEffect(() => { - return () => { - throttledCallback.cancel(); - }; - }, [throttledCallback]); - - return throttledCallback; -} +export const useThrottle = internalUseThrottle; From ead518133d0d1497fd47e1d557df09196133a1e0 Mon Sep 17 00:00:00 2001 From: Antoliny0919 Date: Thu, 19 Nov 2026 14:35:56 +0900 Subject: [PATCH 2/2] apply hyesungoh suggestion - use an explicit inline type in the type test - remove the unnecessary export from DebouncedFunction --- .../src/hooks/_internal/useDebounce/debounce.ts | 2 +- .../src/hooks/_internal/useDebounce/useDebounce.spec.ts | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/react-simplikit/src/hooks/_internal/useDebounce/debounce.ts b/packages/react-simplikit/src/hooks/_internal/useDebounce/debounce.ts index 6fe81a85..20835ce2 100644 --- a/packages/react-simplikit/src/hooks/_internal/useDebounce/debounce.ts +++ b/packages/react-simplikit/src/hooks/_internal/useDebounce/debounce.ts @@ -2,7 +2,7 @@ import type { CallerTypedArgs } from '../../../_internal/types.ts'; -export type DebouncedFunction void> = { +type DebouncedFunction void> = { (...args: Parameters): void; cancel: () => void; }; diff --git a/packages/react-simplikit/src/hooks/_internal/useDebounce/useDebounce.spec.ts b/packages/react-simplikit/src/hooks/_internal/useDebounce/useDebounce.spec.ts index 7e33c365..95a8cc40 100644 --- a/packages/react-simplikit/src/hooks/_internal/useDebounce/useDebounce.spec.ts +++ b/packages/react-simplikit/src/hooks/_internal/useDebounce/useDebounce.spec.ts @@ -2,7 +2,6 @@ import { beforeEach, describe, expect, expectTypeOf, it, vi } from 'vitest'; import { renderHookSSR } from '../../../_internal/test-utils/renderHookSSR.tsx'; -import { DebouncedFunction } from './debounce.ts'; import { useDebounce } from './useDebounce.ts'; describe('useDebounce', () => { @@ -83,7 +82,7 @@ describe('useDebounce', () => { const { result } = renderHookSSR(() => useDebounce(callback, 100)); - expectTypeOf(result.current).toEqualTypeOf>(); + expectTypeOf(result.current).toEqualTypeOf<{ (value: string): void; cancel: () => void }>(); }); it('should cleanup on unmount', async () => {