Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/tall-lions-rush.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'react-simplikit': patch
---

feat(core/hooks): add 'useThrottledCallback' hook
1 change: 1 addition & 0 deletions packages/core/src/hooks/useThrottledCallback/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { useThrottledCallback } from './useThrottledCallback.ts';
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)} />;
}
```
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)} />;
}
```
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);
});
});
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;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: onChange is 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.

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]
);
}
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export { usePrevious } from './hooks/usePrevious/index.ts';
export { useRefEffect } from './hooks/useRefEffect/index.ts';
export { useStorageState } from './hooks/useStorageState/index.ts';
export { useThrottle } from './hooks/useThrottle/index.ts';
export { useThrottledCallback } from './hooks/useThrottledCallback/index.ts';
export { useTimeout } from './hooks/useTimeout/index.ts';
export { useToggle } from './hooks/useToggle/index.ts';
export { useVisibilityEvent } from './hooks/useVisibilityEvent/index.ts';
Expand Down
Loading