Skip to content

Commit cec3206

Browse files
committed
refactor(useThrottledCallback): use named function in 'useEffect', replace 'useMemo' with 'usePreservedReference', and add leading+trailing test
1 parent 4a042c4 commit cec3206

2 files changed

Lines changed: 18 additions & 5 deletions

File tree

packages/core/src/hooks/useThrottledCallback/useThrottledCallback.spec.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,20 @@ describe('useThrottledCallback', () => {
8383
expect(onChange).not.toBeCalled();
8484
});
8585

86+
it('should handle leading and trailing edges together', () => {
87+
const onChange = vi.fn();
88+
const { result } = renderHookSSR(() =>
89+
useThrottledCallback({ onChange, timeThreshold: 100, edges: ['leading', 'trailing'] })
90+
);
91+
92+
result.current(true);
93+
expect(onChange).toBeCalledTimes(1);
94+
expect(onChange).toBeCalledWith(true);
95+
96+
vi.advanceTimersByTime(100);
97+
expect(onChange).toBeCalledTimes(1);
98+
});
99+
86100
it('should handle value toggling', () => {
87101
const onChange = vi.fn();
88102
const { result } = renderHookSSR(() => useThrottledCallback({ onChange, timeThreshold: 100 }));

packages/core/src/hooks/useThrottledCallback/useThrottledCallback.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
import { useCallback, useEffect, useMemo, useRef } from 'react';
1+
import { useCallback, useEffect, useRef } from 'react';
22

33
import { usePreservedCallback } from '../usePreservedCallback/index.ts';
4+
import { usePreservedReference } from '../usePreservedReference/index.ts';
45
import { throttle } from '../useThrottle/throttle.ts';
56

67
type ThrottleOptions = {
@@ -39,16 +40,14 @@ export function useThrottledCallback({
3940
const handleChange = usePreservedCallback(onChange);
4041
const ref = useRef({ value: false, clearPreviousThrottle: () => {} });
4142

42-
useEffect(() => {
43+
useEffect(function cleanupThrottleOnUnmount() {
4344
const current = ref.current;
4445
return () => {
4546
current.clearPreviousThrottle();
4647
};
4748
}, []);
4849

49-
const preservedEdges = useMemo(() => {
50-
return edges;
51-
}, [edges]);
50+
const preservedEdges = usePreservedReference(edges);
5251

5352
return useCallback(
5453
(nextValue: boolean) => {

0 commit comments

Comments
 (0)