Skip to content

Commit d1486a0

Browse files
committed
refactor: simplify delayed state cleanup
1 parent dd526d0 commit d1486a0

2 files changed

Lines changed: 14 additions & 27 deletions

File tree

src/hooks/useDelayState.ts

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -19,17 +19,17 @@ export default function useDelayState<T>(
1919
defaultValue: T | (() => T),
2020
): [T, SetDelayState<T>] {
2121
const [value, setValue] = React.useState(defaultValue);
22-
const rafRef = React.useRef<number | null>(null);
23-
const timeoutRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
22+
const delayRef = React.useRef<[isRaf: boolean, delay: number] | null>(null);
2423

2524
const cancelPending = useEvent(() => {
26-
if (rafRef.current !== null) {
27-
raf.cancel(rafRef.current);
28-
rafRef.current = null;
29-
}
30-
if (timeoutRef.current !== null) {
31-
clearTimeout(timeoutRef.current);
32-
timeoutRef.current = null;
25+
if (delayRef.current) {
26+
const [isRaf, delay] = delayRef.current;
27+
if (isRaf) {
28+
raf.cancel(delay);
29+
} else {
30+
clearTimeout(delay);
31+
}
32+
delayRef.current = null;
3333
}
3434
});
3535

@@ -43,21 +43,19 @@ export default function useDelayState<T>(
4343
typeof immediatelyOrDelay === 'object' &&
4444
'ms' in immediatelyOrDelay
4545
) {
46-
timeoutRef.current = setTimeout(
47-
() => setValue(nextValue),
48-
immediatelyOrDelay.ms,
49-
);
46+
delayRef.current = [
47+
false,
48+
window.setTimeout(() => setValue(nextValue), immediatelyOrDelay.ms),
49+
];
5050
} else {
5151
const frame =
5252
typeof immediatelyOrDelay === 'object'
5353
? immediatelyOrDelay.frame
5454
: undefined;
55-
rafRef.current = raf(() => setValue(nextValue), frame);
55+
delayRef.current = [true, raf(() => setValue(nextValue), frame)];
5656
}
5757
},
5858
);
5959

60-
React.useEffect(() => cancelPending, [cancelPending]);
61-
6260
return [value, setDelayValue];
6361
}

tests/useDelayState.test.tsx

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -130,15 +130,4 @@ describe('useDelayState', () => {
130130
});
131131
expect(result.current[0]).toBe(2);
132132
});
133-
134-
it('cancels pending update on unmount', () => {
135-
const { result, unmount } = renderHook(() => useDelayState(0));
136-
137-
act(() => {
138-
result.current[1](1, { ms: 100 });
139-
});
140-
unmount();
141-
142-
expect(jest.getTimerCount()).toBe(0);
143-
});
144133
});

0 commit comments

Comments
 (0)